﻿import { Component, OnInit, ViewChild } from '@angular/core';
import { Http, Headers, Response, RequestOptions } from "@angular/http";
import { Router, ActivatedRoute, Params } from '@angular/router';
import { MdDialog, MdDialogRef, MdDialogConfig } from '@angular/material';
import { MdSnackBar } from '@angular/material';

import { TfabricaCrudService } from './tfabrica.crud.service';
import { TfabricaCrudReport } from './tfabrica.crud.report.model';
import { TfabricaSharedService } from '../main/tfabrica.shared.service';
import { TfabricaLogService } from '../main/tfabrica.log.service';

import { TfabricaMessageDialogComponent } from '../main/tfabrica.message.dialog.component';

import { TfabricaMessage } from '../models/tfabrica.message.model';
import { TfabricaLog } from '../models/tfabrica.log.model';

import { TfabricaCrudSelectFieldsComponent } from './tfabrica.crud.selectfields.component';
import { TfabricaCrudFilterFieldsComponent } from './tfabrica.crud.filterfields.component';
import { TfabricaDataTableComponent } from './tfabrica.crud.datatable.component';

@Component({
    selector: 't-crud-read',
    template: require('./tfabrica.crud.read.component.html'),
})
export class TfabricaCrudReadComponent implements OnInit {

    public report: TfabricaCrudReport;
    public loading: boolean;

    @ViewChild('trightfiltersmenu') filtersmenu;
    @ViewChild('trightfieldsmenu') fieldsmenu;

    constructor(
        private _http: Http,
        private _sharedService: TfabricaSharedService,
        private _crudService: TfabricaCrudService,
        private _logService: TfabricaLogService,
        private _router: Router,
        private _activatedRoute: ActivatedRoute,
        public dialog: MdDialog,
        public snackBar: MdSnackBar
    ) { 

        this.initReportData();

        /*
        this._activatedRoute.params.subscribe((params: Params) => {
            console.log("Change Parameter!");
            let userId = params['userId'];
            console.log(userId);
        });
        */
        let that = this;
        this._router.events.subscribe(s => {
            //console.log("router Events activated!");
            //console.log(that._router.url);
            //console.log(s);
            if (s.url.startsWith("/main/(main:report)")) {
                console.log("START >> initReportData");
                this.initReportData();
            }
        });
        
    }

    ngOnInit() {
        
    }

    public initReportData() {
        let that = this;
        
        this.report = new TfabricaCrudReport();

        that._sharedService.returnSelectedVoice().properties.forEach(function (entry) {
            //console.log(entry);
            if (entry.key == "Report") {
                //console.log(JSON.parse(entry.value.toString()));
                try {
                    that.report.setFromJson(JSON.parse(entry.value.toString()));
                } catch (Err) {
                    that.report.setFromJson(entry.value);
                }
                //console.log(that.report);
                that.report.setFiltersValuesFromUserParameters(that._sharedService.getUser().parameters);
                that._crudService.initFromReport(that.report);

                //get data from localStorage
                /*
                try {
                    let savedReport = that._crudService.getReport();
                    if (savedReport.title == that.report.title) {
                        that.report = savedReport;
                        that._crudService.initFromReport(that.report);
                    }
                } catch (Err) {
                }
                */

                that._logService.AddLog(new TfabricaLog("initReportData", "initReportData", JSON.stringify(that.report), true));
                
            }
        });

        if (that.report.executeImmediately) {
            this.extractData();
        }

    }

    public extractData() {
        let that = this;
        
        that.loading = true;

        this._crudService.readData(that.report).subscribe(
            reportData => {

                that.report = reportData;


                this._logService.AddLog(new TfabricaLog("Call Report: " + that.report.title, "Command", this.report.composedCommand, true));

                console.log(that.report);
                console.log(that.report.fields);


                that.loading = false;
                //this.router.navigate(['/main', { outlets: { 'main': ['home'] } }]);

                if (that.report.success) {

                } else {
                    this.snackBar.open(that.report.message, "", {
                        duration: 2000,
                    });

                    let newMsg = new TfabricaMessage();
                    newMsg.message = that.report.message;
                    newMsg.success = false;
                    this.displayMessage(newMsg);
                }

            },
            err => {
                // Log errors if any
                console.log(err);
                that.loading = false;
            });
    }

    public displayMessage(message) {
        //this.filtersmenu.toggle();
        let dialogConfig = new MdDialogConfig();
        dialogConfig.data = message;

        let dialogRef = this.dialog.open(TfabricaMessageDialogComponent, dialogConfig);
        dialogRef.afterClosed().subscribe(result => {
            console.log(result);
            if (result != null) {

            }
        });
    }

    public openSearchRight() {
        console.log("filtersmenu.toggle");
        this.filtersmenu.toggle();
    }


    public openSearch() {
        //this.filtersmenu.toggle();

        let dialogConfig = new MdDialogConfig();
        //dialogConfig.width = "95%";
        //dialogConfig.height = "95%";

        let dialogRef = this.dialog.open(TfabricaCrudFilterFieldsComponent, dialogConfig);
        dialogRef.afterClosed().subscribe(result => {
            console.log(result);
            if (result != null) {
                this.report.filters = result;
                this._crudService.setFilters(this.report.filters);
                this.extractData();
            }
        });    
    }

    public startSearch() {
        this.filtersmenu.toggle();
    }


    public openFieldsList() {
        //this.fieldsmenu.toggle();

        let dialogConfig = new MdDialogConfig();

        dialogConfig.width = "95";
        dialogConfig.height = "95";

        console.log("openFieldsList()");
        let dialogRef = this.dialog.open(TfabricaCrudSelectFieldsComponent, dialogConfig);
        dialogRef.afterClosed().subscribe(result =>
        {
            console.log("openFieldsList()");
            console.log("result");
            console.log(result);
            if (result != null) {
                this.report.setFields(result);
                this._crudService.setFields(this.report.fields);                
                console.log("this.report.fields");
                console.log(this.report.fields);
                console.log("this.report.fieldsToDisplay");
                console.log(this.report.fieldsToDisplay);
            }
        });    

    }

    public setFieldsList() {
        this.fieldsmenu.toggle();
    }

    public addNewRow() {
        this._crudService.setOperation("I");
        this._crudService.setSelectedRow(new Object());
        this._crudService.setReport(this.report);
        this._router.navigate(['/main', { outlets: { 'main': ['reportDetail'] } }]);
    }

    public goToDetail(row) {
        console.log("Go To Detail:");
        console.log(row);
        this._crudService.setOperation("U");
        this._crudService.setSelectedRow(row);
        this._crudService.setReport(this.report);
        this._router.navigate(['/main', { outlets: { 'main': ['reportDetail'] } }]);
    }

    public onRowClicked(row) {
        console.log(row);
        this.goToDetail(row);
    }


}