import {Component, OnInit} from '@angular/core';
import {Api} from '../../service/api';
import {NavController} from '@ionic/angular';
import {ActivatedRoute, Router} from '@angular/router';
import {Load} from '../../service/load';
import {Transfer} from '../../service/transfer';
import {DatePipe} from '@angular/common';

@Component({
    selector: 'v-env-change-model',
    templateUrl: './env-change-model.page.html',
    styleUrls: ['./env-change-model.page.scss'],
})
export class EnvChangeModelPage implements OnInit {

    constructor(public nav: NavController,
                private api: Api,
                private ac: ActivatedRoute,
                private load: Load,
                private tf: Transfer,
                private router: Router,
                private datePipe: DatePipe) {}

    controlConfig = [];
    ngOnInit() {
        this.init();
    }

    init() {
        this.controlConfig = [{id: 1, config: {id: 1, name: '', startDate: '', stopDate: '', on: '', off: ''}}];
    }

    addModel() {
        const modelCount = this.controlConfig.length;
        this.controlConfig.push({
            id : modelCount + 1,
            config: {id: modelCount + 1, name: '', startDate: '', stopDate: '', on: '', off: ''}});
    }

    deleteModel(one) {
        const updateModel = this.controlConfig.filter(data => data.id !== one.id);
        this.controlConfig = updateModel;
        this.controlConfig.forEach((item, index) => {
            item.id = index + 1;
            item.config.id = index + 1;
        });
    }

    saveModels() {
        this.controlConfig.forEach((item, index) => {
            item.id = index + 1;
            item.config.id = index + 1;
            item.config.on = this.formatTime(item.config.on);
            item.config.off = this.formatTime(item.config.off);
            item.config.startDate = this.formatDate(item.config.startDate);
            item.config.stopDate = this.formatDate(item.config.stopDate);
        });
        const query = '?changeModelCfg=' + JSON.stringify(this.controlConfig);
        // this.nav.navigateForward('', );
        // this.nav.navigateBack()
        // this.nav.navigateBack('', {changeModels: this.controlConfig});
        // this.router.navigate(['/tabs/tab-cfg'], { queryParams: { changeModelCfg: this.controlConfig } });
        this.nav.navigateBack('/tabs/tab-cfg' + query);
    }

    goBack() {
        this.nav.back();
    }

    formatTime(time) {
        return this.datePipe.transform(time, 'HH:mm');
    }

    formatDate(date) {
        return this.datePipe.transform(date, 'MM-dd');
    }
}
