import {Component, ElementRef, OnInit} from '@angular/core';
import {ActivatedRoute, Router} from "@angular/router";
import {HelpContentService} from "../../services/help-content.service";
import {
  FormArray,
  FormGroup,
  UntypedFormArray,
  UntypedFormBuilder,
  UntypedFormGroup,
  ValidatorFn,
  Validators
} from "@angular/forms";
import {Page} from "../../utils/entities/adminTool/page";
import {EnvProperties} from '../../utils/properties/env-properties';
import {HelperFunctions} from "../../utils/HelperFunctions.class";
import {Subscriber} from "rxjs";
import {properties} from "../../../../environments/environment";
import {PortalUtils} from "../portal/portalHelper";
import {Option} from "../../sharedComponents/input/input.component";
import {Title} from "@angular/platform-browser";
import {ClearCacheService} from "../../services/clear-cache.service";
import {NotificationHandler} from "../../utils/notification-handler";
import {PluginsService} from "../../services/plugins.service";
import {Plugin} from "../../utils/entities/adminTool/plugin";
import {StringUtils} from "../../utils/string-utils.class";
import {Portal} from "../../utils/entities/adminTool/portal";
import {PluginTemplate} from "../../utils/entities/adminTool/pluginTemplate";
import {PluginUtils} from "./utils/pluginUtils";
import {CommunityService} from "../../connect/community/community.service";
import {CommunityInfo} from "../../connect/community/communityInfo";
import {PluginEditEvent} from "./utils/base-plugin.form.component";

@Component({
  selector: 'plugins',
  templateUrl: './plugins.component.html',
})
export class PluginsComponent implements OnInit {
  private selectedId: string;
  public pluginsByPlacement: Map<string,{plugin:Plugin, template:PluginTemplate, openPreview:boolean}[]> = new Map();
  public plugins: Plugin[] = [];
  public pluginTemplates: PluginTemplate[] = [];
  public selectedTemplate: PluginTemplate = null;
  public selectedPlugin: Plugin = null;
  public editView = false;
  public selectTemplateView = false;
  public templateForm: UntypedFormGroup;
  public pagesCtrl: UntypedFormArray;
  urlValidator: ValidatorFn = StringUtils.urlValidator;
  private searchText: RegExp = new RegExp('');
  public keyword: string = "";
  public properties: EnvProperties = properties;
  public formPages: Page[] = [];
  public showLoading: boolean = true;
  private subscriptions: any[] = [];
  public allPages: Option[] = [];
  public pluginUtils = new PluginUtils();
  selectedCommunityPid = null;
  public portalUtils: PortalUtils = new PortalUtils();
  private index: number;
  public portal: string;
  public selectedPageId: string;
  public community: Portal;
  public page: Page;
  public templateView = false;
  public templateCode:string = null;
  public template;
  public selectedPlacementView = "all";
  public sinlgePlacementAvailable = false;
  communityInfo:CommunityInfo = null;
  editSubmenuOpen = false;
  constructor(private element: ElementRef, private route: ActivatedRoute, private _router: Router,
              private communityService: CommunityService,
              private title: Title, private _helpContentService: HelpContentService,
              private _pluginsService: PluginsService, private _fb: UntypedFormBuilder,
              private _clearCacheService: ClearCacheService) {
  }

  ngOnInit() {
    this.title.setTitle('Administrator Dashboard | Plugins');
    this.subscriptions.push(this.communityService.getCommunityAsObservable().subscribe(
      community => {
        this.communityInfo = community;
      }));
    this.subscriptions.push(this.route.params.subscribe(params => {

      this.portal = (this.route.snapshot.data.portal) ? this.route.snapshot.data.portal : this.route.snapshot.params[this.route.snapshot.data.param];
      this.selectedCommunityPid = params.community;

      this.subscriptions.push(this.route.queryParams.subscribe(params => {
        HelperFunctions.scroll();
        this.selectedPageId = params['pageId'];
        if (this.portal && this.selectedPageId) {
          this.getPage(this.selectedPageId);
        }
        if (!this.selectedPageId && !this.templateView) {
          this._router.navigate(['../pages'], {relativeTo: this.route});
        }
      }));
    }));

  }

  ngOnDestroy(): void {
    this.subscriptions.forEach(value => {
      if (value instanceof Subscriber) {
        value.unsubscribe();
      } else if (value instanceof Function) {
        value();
      }
    });
  }

  getTemplateById(id) {
    for (let template of this.pluginTemplates) {
      if (template._id == id) {
        return template;
      }
    }
    return null;
  }

  getPage(pageId: string) {
    this.showLoading = true;
    this.subscriptions.push(this._helpContentService.getPageByPortal(pageId, this.properties.adminToolsAPIURL, this.portal).subscribe(
      page => {
        if (this.properties.adminToolsPortalType != page.portalType) {
          this._router.navigate(['./pageContents']);
        } else {
          this.page = page;
          this.getPagePlugins();
        }
      },
      error => this.handleError('System error retrieving page', error)));
  }

  getPagePlugins() {
    this.showLoading = true;
    this.subscriptions.push(this._pluginsService.getPluginTemplatesByPage(this.properties.adminToolsAPIURL, this.selectedCommunityPid, this.selectedPageId).subscribe(
      templates => {
        this.pluginTemplates = templates;

        this.subscriptions.push(this._pluginsService.getPluginsByPage(this.properties.adminToolsAPIURL, this.selectedCommunityPid, this.selectedPageId).subscribe(
          plugins => {
            this.plugins = plugins;
            this.pluginsByPlacement = new Map();
            for(let pos of this.pluginUtils.placementsOptions){
              this.pluginsByPlacement.set(pos.value,[]);
            }
            let self = this;
            this.pluginTemplates.forEach(_ => {
              let plugin:Plugin = null;
              for(let pl of plugins){
                if (pl.templateId == _._id){
                  plugin = pl;
                }
              }
              if(!plugin){
                plugin = new Plugin(this.selectedPageId, this.selectedCommunityPid,_);
                this.plugins.push(plugin);
              }
              plugin.object = PluginUtils.initializeObjectAndCompare(_.code,plugin.object)
              this.pluginsByPlacement.get(plugin.placement).push({plugin: plugin, template: _ , openPreview:false});
            });
            let availablePlacements = [];
            for(let placement of this.pluginUtils.placementsOptions){
              if(this.pluginsByPlacement.get(placement.value).length > 0){
                availablePlacements.push(placement.value);
              }
              this.pluginsByPlacement.get(placement.value).sort(function (a, b) {
                return a.plugin.order - b.plugin.order;
              })
            }
            if(availablePlacements.length == 1){
              this.selectedPlacementView == availablePlacements[0];
              this.sinlgePlacementAvailable = true
            }
            this.showLoading = false;
          },
          error => this.handleError('System error retrieving plugins', error)));

      },
      error => this.handleError('System error retrieving templates', error)));
  }

  public edit(plugin:Plugin, template:PluginTemplate, placement, index) {
    this.editView = true;
    this.selectedPlugin = JSON.parse(JSON.stringify(plugin)); // deep copy object with nested objects
    this.selectedTemplate = template;
    this.index = index;
    this.pagesCtrl = this._fb.array([], Validators.required);
    this.templateForm = this._fb.group({
      _id: this._fb.control(plugin._id),
      pid: this._fb.control(this.selectedCommunityPid),
      page: this._fb.control(plugin.page),
      templateCode: this._fb.control(plugin.templateCode, Validators.required),
      templateId: this._fb.control(plugin.templateId, Validators.required),
      placement: this._fb.control(plugin.placement),
      order: this._fb.control(plugin.order),
      active: this._fb.control(plugin.active),
      values: this._fb.array([]),
    });

    if (template.settings) {
      for (let attrKey of Object.keys(template.settings)) {
        (this.templateForm.get("values") as FormArray).push(this._fb.group({
            'key': this._fb.control(attrKey),
            'value': this._fb.control(plugin.settingsValues[attrKey]?plugin.settingsValues[attrKey]:template.settings[attrKey].value)
          }
        ));
      }
    }
  }

  public newPluginSelectTemplate() {
    this.selectedPlugin = null;
    this.editView = true;
    if(!this.templateView) {
      this.selectedTemplate = null;
      this.selectTemplateView = true;
    }else{
      this.newPlugin( Object.assign({}, this.template));
    }
  }

  public newPlugin(template) {
    this.selectedTemplate = template;
    this.templateForm = this._fb.group({
      _id: this._fb.control(null),
      pid: this._fb.control(this.selectedCommunityPid),
      page: this._fb.control(this.selectedPageId),
      code: this._fb.control(this.selectedTemplate.code, Validators.required),
      placement: this._fb.control(this.selectedTemplate.placement),
      order: this._fb.control(""),
      active: this._fb.control(false),
      isPriorTo: this._fb.control(false),
      values: this._fb.array([]),
      object: this._fb.control({})
    });
    for (let attrKey of Object.keys(this.selectedTemplate.settings)) {
      (this.templateForm.get("values") as FormArray).push(this._fb.group({
        key: this._fb.control(attrKey),
        value: this._fb.control(this.selectedTemplate.settings[attrKey].value ? this.selectedTemplate.settings[attrKey].value : ""),
      }));

    }
    this.selectTemplateView = false;

  }

  public saveConfirmed(index) {
    this.showLoading = true;
    let plugin: Plugin = <Plugin>this.templateForm.getRawValue();
    plugin.object = this.selectedPlugin.object;
    plugin.settingsValues = new Map<string, string>();
    for (let fields of this.templateForm.getRawValue().values) {
      plugin.settingsValues[fields.key] = fields.value;
    }
    let update = (plugin._id) ? true : false;
    this.savePlugin(plugin,update, this.index)
  }
  public savePlugin(plugin, update, index){
    this.subscriptions.push(this._pluginsService.savePlugin(plugin, this.properties.adminToolsAPIURL, this.selectedCommunityPid).subscribe(
      saved => {
        this.savedSuccessfully(saved, update, index);
        this.editView = false;
        this.selectTemplateView = false;
        this.selectedTemplate = null;
        this.selectedPlugin = null;
        this.clearCache();
      },
      error => this.handleUpdateError("System error creating template", error)
    ));
  }

  public savedSuccessfully(plugin: Plugin, update: boolean, index) {
    console.log(plugin.placement, index, update)
    if (update) {
      this.pluginsByPlacement.get(plugin.placement)[index].plugin = plugin;
    } else {
      this.plugins.push(plugin);
    }
    this.showLoading = false;
  }

  public filterPlugins(plugin: Plugin, template: PluginTemplate): boolean {
    let values =[];
    for(let key of this.getKeys(plugin.settingsValues)){
      values.push(plugin.settingsValues[key]);
    }
    return this.searchText.toString() == '' || (plugin.templateCode + ' ' +values.join(' ') +   (template?(template.name + ' ' +template.description):'')).match(this.searchText) != null;
  }


  handleUpdateError(message: string, error = null) {
    if (error) {
      console.log('Server responded: ' + error);
    }
    NotificationHandler.rise(message, 'danger');
    this.showLoading = false;
  }

  handleError(message: string, error = null) {
    if (error) {
      console.log('Server responded: ' + error);
    }
    NotificationHandler.rise(message, 'danger');
    this.showLoading = false;
  }

  getPages() {
    this.showLoading = true;
    this.subscriptions.push(this._helpContentService.getAllPages(this.properties.adminToolsAPIURL).subscribe(
      pages => {
        this.allPages = [];
        pages.forEach(page => {
          this.allPages.push({
            label: page.name + " [" + page.portalType + "]",
            value: page
          });
        });
        this.showLoading = false;
      },
      error => this.handleError('System error retrieving pages', error)
    ));
  }

  get attrFormArray() {

    return this.templateForm.get("values") as FormArray;

  }

  attributeTypeChanged(form) {
    let type = form.get("value").get("type");
    form.get("value").setValue("");
    if (type == "boolean") {
      form.get("value").setValue(false);
    }
  }

  public getPagesAsString(pageIds): string {

    let pages = [];
    for (let id of pageIds) {
      pages.push(this.allPages.filter(option => option.value._id == id).map((option => option.value.name)));

    }
    return pages.join(", ");
  }

  public getPageById(pageId) {
    for (let option of this.allPages) {
      if (option.value._id == pageId) {
        return option.value;
      }
    }
    return pageId;
  }

  getKeys(obj) {
    return obj?Object.keys(obj):[];
  }

  reset() {
    if (this.selectedPlugin) {

      this.edit(this.pluginsByPlacement.get(this.selectedTemplate.placement)[this.index].plugin, this.selectedTemplate, this.selectedTemplate.placement, this.index)
    } else {
      this.newPlugin(this.selectedTemplate)
    }
  }


  public togglePlugin(status: boolean, id: string,i, placement) {
    this.index = i;
    this.selectedTemplate = this.pluginsByPlacement.get(placement)[i].template;
    if(id) {
      this.subscriptions.push(this._pluginsService.togglePlugin(id, status, this.properties.adminToolsAPIURL, this.selectedCommunityPid).subscribe(
        () => {

          this.pluginsByPlacement.get(placement)[i].plugin.active = status;
          this.clearCache();
        },
        error => this.handleUpdateError('System error changing the status of Plugin', error)
      ));
    }else{
      let plugin = this.pluginsByPlacement.get(placement)[i].plugin;
      plugin.active = status;
      this.savePlugin(plugin, true, i);
    }
  }
  pluginFieldChanged($event:PluginEditEvent){
    if($event.type == "open-submenu"){
      this.editSubmenuOpen = true;
      return;
    }
    if($event.type == "close-submenu"){

      this.editSubmenuOpen = false;
      return;
    }
    this.selectedPlugin.object[$event.field]=$event.value;
    this.templateForm.markAsDirty();
  }

  public swap(pluginToMoveUp, pluginToMoveDown, placement ){
    this.showLoading = true;
    let moveUpGroup = this.pluginsByPlacement.get(placement)[pluginToMoveUp];
    let moveDownGroup = this.pluginsByPlacement.get(placement)[pluginToMoveDown];
    this.pluginsByPlacement.get(placement)[pluginToMoveUp] = moveDownGroup;
    this.pluginsByPlacement.get(placement)[pluginToMoveDown] = moveUpGroup;
    this.move(moveUpGroup.plugin,true, pluginToMoveDown, placement);
    this.move(moveDownGroup.plugin,false, pluginToMoveUp, placement);
    this.showLoading = false;
  }
  public move(plugin: Plugin, up:boolean, index, placement) {
    if(plugin._id) {
      this.subscriptions.push(this._pluginsService.updatePluginOrder(plugin, this.properties.adminToolsAPIURL, up ? -1 : 1, this.selectedCommunityPid).subscribe(
        saved => {
        this.pluginsByPlacement.get(placement)[index].plugin = saved;
        this.clearCache();
        },
        error => this.handleUpdateError("System error creating template", error)
      ));
    }else{

      plugin.order = plugin.order + (up ? -1 : 1)
      this.savePlugin(plugin, true, index);
    }


  }
  clearCache(){
    this._clearCacheService.clearCacheInRoute(null, this.selectedCommunityPid,  this.getPageById(this.selectedPageId).route)
  }
}
