import { Component, OnInit }                        from "@angular/core"
import { Params, ActivatedRoute }                   from '@angular/router'
import { Location } from '@angular/common';

import { StorelocatorService }                      from '../../../services/svc.store-locator'
import { StudioService }                            from '../../../services/svc.studios'
import { HelperService }                            from '../../../services/svc.helper'

import { PageService }      from '../../../services/svc.page';
import { PageType }         from '../../../types/page';
import { SeoService }       from '../../../services/svc.seo'

@Component({
    moduleId: module.id+ '',
    selector: 'find-store',
    templateUrl: './tpl.find-store.pug',
    styleUrls: ['./sty.find-store.scss']
})

export class FindStoreView {

    store: any;
    stores: any;

    studio: any;

    pageContent: PageType

    filteredStores: Array<any> = [];
    types: any;

    specificStore: boolean = false;

    constructor(
        private _route: ActivatedRoute,
        private storelocatorService: StorelocatorService,
        private studioService: StudioService,
        private _helper: HelperService,
        private _location: Location,
        private _page: PageService,
        private _seo: SeoService
    ) {

    }

    server: string = this._helper.server

    ngOnInit() {


        // Get current location, strip first occurrence of `/`
        let urlKey:string = this._location.path();

        if(urlKey.match(/\/.+/)){
            urlKey = urlKey.replace('/', '');
        }

        if(urlKey.indexOf('/') > -1) {
            urlKey = urlKey.split('/')[0]
        }


        // Get page content
        this._page.getPageContent(urlKey)
            .then((content) => {
                this.pageContent = content;

                // Set SEO
                this._seo.setTitle(content.meta.title);
                this._seo.updateTag('description', content.meta.description);
            });

        this.storelocatorService.getTypes().then(response => {
            this.types = response
        })

        this._route.params.subscribe((params: any) => {

            if(!!params.studio) {
                this.specificStore = true;
            }

            let isSet = false;

            console.log(params)

            // Found store on Parameters
            if(!!params.store && !isSet) {
                this.storelocatorService.findStoreByUrlkey(params.store).then(response => {
                    this.store = response.store
                    this.stores = '';

                    if(this.store.state) {
                        this.studioService.getStudios().then(response => {

                            this.studio = '';

                            try {
                                for(let studio of response.blocks) {
                                    if(studio.settings.state == this.store.state) {
                                        this.studio = studio.settings
                                    }
                                }
                            }
                            catch(err) {
                                // TODO: fix error when there is time.
                                //console.log(err);
                            }


                        })

                    }

                })

                
                isSet = true;
            }

            // Found state on Parameters
            if(!!params.state && !isSet) {

                this.storelocatorService.findStoresByState(params.state).then(response => {
                    this.filterStore(response)
                })

                this.studioService.getStudios().then(response => {

                    this.studio = '';

                    for(let studio of response.blocks) {

                        if(studio.settings.state == params.state) {
                            this.studio = studio.settings
                        }
                    }

                })


                isSet = true;
            }

            // Found countries on parameters
            if(!!params.country && !isSet) {
                this.storelocatorService.findStoresByCountry(params.country).then(response => {
                    this.filterStore(response)
                    
                })
                isSet = true;
            }
        })
    }

    filterStore(data) {

        this.filteredStores = []

        if(!!data.stores) {

            // If only 1 store is returned, display store
            if(data.stores.length == 1) {
                this.store = data.stores[0]
                this.stores = '';
                
            } else if(data.stores.length > 1) {
                this.stores = data

                // Sort stores by type
                for(let store of this.stores.stores) {
                    if(!!store.type) {

                        // Create sub-array if it doesn't exist
                        if(!!!this.filteredStores[store.type]) {
                            this.filteredStores[store.type] = []
                        }
                        
                        this.filteredStores[store.type].push(store)
                    }    
                } 

                this.store = '';
            }

        }

    }
}