import {Injectable} from '@angular/core';
import {Store} from '@ngrx/store';
import * as appCommonReducer from '../reducers/app-common.reducer';
import {IPackage, IPackages} from '../models/package';

import {IItem} from '../models/item';
import {IItemTask} from '../models/itemTask';
import { HttpClient } from '@angular/common/http';
import {AppConfig} from '../shared/app.config';
import {Observable,iif,of} from 'rxjs';
import {switchMap} from 'rxjs/operators';

@Injectable({
  providedIn: 'root',
})

export class PackageService {
  private userPackages: { [key: string]: IPackage } = {};
  private packages: { [key: string]: IPackage } = {};
  private packagesObservable = this.store$.select(appCommonReducer.SelectGetPackages);

  constructor(private store$: Store<appCommonReducer.State>, public httpClient: HttpClient, public appConfig: AppConfig) {
    store$.select(appCommonReducer.SelectGetValidUserPackages).subscribe((packages) => {
      this.userPackages = packages;
    });
    this.packagesObservable.subscribe((packages) => {
      this.packages = packages;
    });
  }

  ApiEndpoint() {
    return this.appConfig.getConfig('apiEndPoint');
  }

  hasPackage(id: string): boolean {
    return id in this.userPackages;
  }

  packageExists(id: string): boolean {
    return id in this.packages;
  }

  postItemPackageTask(item: IItem, task: IItemTask): Observable<IItemTask> {
    return this.httpClient.post<IItemTask>(`${this.ApiEndpoint()}/api/v1/items/${item.code}/packagetasks`, task);
  }

  ifPackageListExists<Type>(packageList: Array<string>, ifTrue:Observable<Type>,ifFalse:Observable<Type>):Observable<Type> {
    return this.packagesObservable.pipe(switchMap(packages => 
        iif(( )=> Object.keys(packages).some(id => packageList.includes(id)),
            ifTrue,
            ifFalse) 
    )); 
  }
}

export function getValidPackages(packageMap: IPackages): {[key: string]: IPackage} {
  const keys = Object.keys(packageMap);
  return keys.filter(k => {
    const packages = packageMap[k]
      .filter((p) => isValidPackage(p));

    return packages.length > 0;
  }).reduce((map, key) => {
    const packages = packageMap[key];
    const newMap = {...map};
    newMap[key] = packages.find(p => isValidPackage(p));
    return newMap;
  }, {});
}

export function isValidPackage(pack: IPackage): boolean {
  const now = new Date(Date.now());
  const utcToday = Date.UTC(now.getUTCFullYear(),now.getUTCMonth(),now.getUTCDate());
  return pack !== null && new Date(pack.dataDate).getTime() <= utcToday
    && (!pack.dataEndDate || new Date(pack.dataEndDate).getTime() >= utcToday);

}
