import { Injectable } from '@angular/core';
import {IItemTypes} from '../models/item.types'
import {IItem} from '../models/item'
import {AppConfig} from '../shared/app.config';
import { HttpClient, HttpXhrBackend } from '@angular/common/http';

@Injectable()
export class ItemTypeService {
    public itemTypes: IItemTypes;
    private httpClient: HttpClient;

    constructor(xhrBackend: HttpXhrBackend) {
      this.httpClient = new HttpClient(xhrBackend);
    }

     getIcon(itemType: string) {
       let icon = "fal fa-file";
       if (this.itemTypes && this.itemTypes[itemType]) icon = this.itemTypes[itemType].icon;
       return icon;
     }

     getColor(itemType: string) {
       let color = "#000000";
       if (this.itemTypes && this.itemTypes[itemType]) color = this.itemTypes[itemType].iconColor;
       return color;
     }

     getExtraAttributes(itemType: string) {
      let extraAttributes = null;
      if (this.itemTypes && this.itemTypes[itemType] && this.itemTypes[itemType]?.extraAttributes) extraAttributes = this.itemTypes[itemType]?.extraAttributes;
      return extraAttributes;
    }

    getSchema(itemType: string): string {
      let schema = null;
      if (this.itemTypes && this.itemTypes[itemType]) schema = this.itemTypes[itemType].schema;
      return schema;
    }

     hasViewer(item: IItem) {
        const itemType: string = item.itemType;
        if (this.itemTypes && this.itemTypes[itemType]) return this.itemTypes[itemType].viewer !== undefined;
        return false;
      }

      hasEditor(item: IItem) {
        const itemType: string = item.itemType;
        if (this.itemTypes && this.itemTypes[itemType]) return this.itemTypes[itemType].editor !== undefined;
        return false;
      }

      isLayer(item: IItem) {
        const itemType: string = item.itemType;
        return itemType == "vnd.farmmaps.itemtype.geotiff.processed" || itemType == "vnd.farmmaps.itemtype.layer" || itemType == "vnd.farmmaps.itemtype.shape.processed";
      }

      public load(config:AppConfig): Promise<any> {
        if(this.itemTypes==null) {
          const url = `${ config.getConfig("apiEndPoint")}/api/v1/itemtypes/`
          return this.httpClient.get(url)
            .toPromise()
            .then((itemTypes:IItemTypes) => {
              this.itemTypes = itemTypes;
              //return data;
            })
            .catch(error => this.itemTypes = null);  
        } else {
          return new Promise<void>((resolve) => {resolve()});
        }
      }
}
