<app>
  
  <div id="app_header" if={store.cid}>
    <header>
      <app-header />
      <app-tabs ref="tabs" tags={_tags} save_tabs={save_tabs} />
    </header>
  </div>
  
  <div id="app_body" class="{'noheader' : !store.cid }">
  
    <div id="views" ref="body">
      
      <notice></notice>
      
    </div>
    
    <div id="app_guide" if={store.cid && user && check_permission('modify_company', user)}>
      <welcome-guide/>
    </div>
    
    <app-footer if={store.cid} />
    
    <!-- little notification of connection state on bottom -->
    <div class="tags connection-state {!harmony.connected ? '' : 'connected'}">
      <div class="tag object"><small>Reconnecting....</small></div>
    </div>
  
  </div>

  <script>
    'use strict';
    
    

    harmony._on('connect', ()=>{
      harmony.connected = true;
      this.update();
    })
    harmony._on('disconnect', ()=>{
      harmony.connected = false;
      this.update();
    })

    //console.log(this.store);
    /**
     * When the token changes, extract the
     * comes from login.tag
     *   profile,
     *   uid,
     *   cid,
     * We removed this from the token listener, because the header, for example
     * would get the notification before here and it would cause an error
     */
    window.set_token = (token)=>{
      try{
        this.store.token = token;
        let parts = '', decode = {};
        parts = token.split('.');
        decode = JSON.parse(atob(parts[1]));
        this.store.uid = decode.uid || null;
        this.store.cid = decode.cid || null;
        this.store.permissions = decode.permissions || {};
        this.storage.set('store', this.store);
        this.fetch_user()
      }catch(e){
        this.store.uid = null;
        this.store.cid = null;
        this.store.permissions = null;
        this.storage.set('store', this.store);
        if(token !== null){ // we have a token, but it's messed up; allow null
                            // in case we purposefully delete the token
          page.redirect('/logout');
        }
      }
      this.update();
      this.messenger.emit('token', token)
    }

    /**
     * Tag format
     * {
     *  __: {
     *    tagName:
     *  },
     *  __active: <boolean>
     *  opts: {
     *    uuid: <used by tag as params, not concerned with tabs>
     *    tab: {
     *      uuid: <tab uuid>,
     *      close: <is tab set for close>,
     *      title: <default tab title>,
     *      type:
     *    }
     *  }
     * }
     */

    const tl = new TimelineLite({
      onComplete: ()=>{},
      paused: true,
    });
    tl.autoRemoveChildren = true;

    this._tags = (JSON.parse(localStorage.getItem('tabs')) ? JSON.parse(localStorage.getItem('tabs'))[this.store.cid] : null) || [];

    // When the token (aka, company) changes, load the company tabs
    this.messenger.on('token', ()=>{
      if(!this.store.cid) return
      for(let tag of this._tags){
        if(typeof tag.unmount == 'function')
          tag.unmount();
      }
      this._tags = (JSON.parse(localStorage.getItem('tabs')) ? JSON.parse(localStorage.getItem('tabs'))[this.store.cid] : null) || [];
      this.update()
    })

    this.save_tabs = ()=>{
      if(!this.store.cid) return

      // close any extra tags before storing
      this.close_max_tags()

      let clone = []
      for(let tag of this._tags){
        clone.push({
          __: {
            tagName: tag.__.tagName
          },
          opts: {
            tab: tag.opts.tab
          }
        })
      }
      // Each company gets it's own set of tabs
      let current = JSON.parse(localStorage.getItem('tabs')) || {}
      current[this.store.cid] = clone
      localStorage.setItem('tabs', JSON.stringify(current))
    }

    this.close_max_tags = () => {
      if(!this.user || !this.user.max_tags) return
      let total_to_close = Math.max(0, this._tags.length - (this.user.max_tags || 100))
      let old = this._tags.splice(1, total_to_close)
      try{
        for(let tag of old){
          if(tag.root) tag.unmount()
        }
      }catch(e){
        this.show_errors(e)
      }
    }

    // Cleanup orphan tabs
    for(let i = 0; i<this._tags.length; i++){
      if(!this._tags[i].opts || !this._tags[i].opts.tab || this._tags[i].opts.tab.close){
        this._tags.splice(i, 1)
        i--;
      }
    }
    this.save_tabs()

    //gets user so that we can access their max_tags property
    this.fetch_user = async () => {
      try{
        let res = await harmony.get('/user', {
          token: this.store.token,
          me: true
        })
        if (res.code != 200) throw res.errors;
        this.user = res.users[0]
        this.update()

        this.close_max_tags() // once we have the user, close any extra tabs

      }catch(e){
        this.show_errors(e)
      }
    }

    this.route = (ctx, tagName, opts = {})=>{

      // Merge in opts, params, query
      for(let i in ctx.params){
        opts[i] = ctx.params[i]
      }
      for(let i in ctx.query){
        opts[i] = ctx.query[i];
      }

      // Add route to global space
      for(let i in this.router){
        delete this.router[i];
      }
      for(let i in ctx){
        this.router[i] = ctx[i]
      }

      opts.tagName = tagName

      let mounted = false

      for(let i=0; i<this._tags.length; i++){

        let tag = this._tags[i]
        tag.__active = false;

        //This is where max_tags should be checked
        //remove first tags if tags.length is too great


        /**
         * Same tagname and same uuid so reuse it
         * If tab is set to close, skip this so it will be removed below
         */
        if(tag.__.tagName == opts.tagName && tag.opts && tag.opts.tab && opts.tab && tag.opts.tab.uuid == opts.tab.uuid && !tag.opts.tab.close){
          mounted = tag

          // use tag title, instead of stored title in case tag internally changed it
          if(tag.opts && tag.opts.tab && tag.opts.tab.title) opts.tab.title = tag.opts.tab.title
          for(let i in opts){
            tag.opts[i] = opts[i]
          }

          tag.opts.tab.url = ctx.canonicalPath;
          tag.__active = true;
          if(typeof tag.update == 'function') tag.update();
          if(!tag.root) continue; // we have a tab, but it's not mounted
          tl.add( TweenLite.to(tag.root, .3, {
            bottom: '0%',
            opacity: 1,
            pointerEvents: 'all',
            zIndex: 'auto',
          }), '0');

        /**
         * It's a tab (but not same uuid), move it over and leave mounted, unless...
         * If tab is set to close, don't do this and let the next if remove it
         */
        }else if(tag.opts.tab && !tag.opts.tab.close){
          if(!tag.root) continue; // maybe from refresh?
          tl.add( TweenLite.to(tag.root, .3, {
            bottom: '-20%',
            opacity: 0,
            pointerEvents: 'none',
            zIndex: '-1',
          }), '0');

        /**
         * Remove it
         */
        }else{
          this._tags.splice(i, 1);
          i--;
          if(!tag.root) continue; // maybe from refresh?
          tl.add( TweenLite.to(tag.root, .3, {
            bottom: '-20%',
            opacity: 0,
            pointerEvents: 'none',
            zIndex: '-1',
            onComplete: ()=>{
              tag.unmount();
            }
          }), '0');
        }
      }


      if(!mounted || (mounted && !mounted.root)){
        let el = document.createElement('div');
        el.style.position = 'absolute';
        el.style.width = '100%';
        el.style.height = '100%';
        el.style.top = 'auto';
        el.style.opacity = 0;
        el.style.backgroundColor = '#F1F8FE';
        el.style.left = '0%';
        el.style.bottom = '0%';
        el.style.pointerEvents = 'all';
        el.style['box-sizing'] = 'border-box';
        el.style.overflow = 'scroll';
        el.style.zIndex = 'auto';
        this.refs.body.appendChild(el);

        for(let tg of riot.mount(el, tagName, opts)){
          if(typeof tg.opts.tab == 'object') tg.opts.tab.url = ctx.canonicalPath;
          tg.__active = true;

          for(let i=0; i<this._tags.length; i++){
            if(this._tags[i] === mounted){
              this._tags.splice(i, 1, tg)
            }
          }

          if(!mounted) this._tags.push(tg); // we might have to wait for it to be mounted, so if this loop gets called again, we don't run into mount issues

          tl.add( TweenLite.to(tg.root, .3, {
            bottom:'0%',
            opacity: 1,
            pointerEvents: 'all',
            zIndex: 'auto',
            onComplete: ()=>{}
          }), '0');
        }
      }

      this.save_tabs()

      if(this.refs.tabs && typeof this.refs.tabs.update == 'function')
        this.refs.tabs.update()



      tl.play()
    }


    /**
     * Router
     */
    this.on('mount', ()=>{

      page.base('/');

      page('*', (ctx, next)=>{

        console.log('route', ctx)

        ctx.query = qs.parse(ctx.path.split('?')[1]);
        //ctx.query = qs.parse(ctx.querystring); if a plus sign exist, it breaks. See line 110 in query-string.js
        //ctx.query = qs.parse(location.search.slice(1)) // this does not work with changing and updating urls
        next();
      })

      /**
       * These are pages that DO NOT require a token.
       */

      page('check-email', (ctx)=>{
        this.route(ctx, 'check-email');
      })

      page('login', (ctx)=>{
        this.route(ctx, 'login', {wide: true})
      })

      page('signup', (ctx)=>{
        this.route(ctx, 'login', {wide: true, login: false})
      })

      page('forgot-password', (ctx)=>{
        this.route(ctx, 'forgot-password', {wide: true})
      })

      page('user/password/:token', (ctx)=>{
        this.route(ctx, 'password-reset', {wide: true})
      })

      // this requires a token, but it's the token from the email in the url
      page('user/verify/:token', (ctx)=>{
        this.route(ctx, 'verify-token');
      })

      page('user/email/verify/:token', (ctx)=>{
        this.route(ctx, 'verify-email-token');
      })

      // this requires a token, but it's the token from the email in the url
      page('invite/accept/:token', (ctx)=>{
        this.route(ctx, 'invite');
      })

      // Check if token exists
      page('*', (ctx, next)=>{
        if(!this.store.token) return page('/login');
        next();
      })

      /**
       * These are pages that DO require a token.
       */

      page('logout', (ctx)=>{
        this.route(ctx, 'logout');
      })

      page('select-company', (ctx)=>{
        this.route(ctx, 'select-company')
      })

      page('client/:uuid', (ctx)=>{
        this.route(ctx, 'client', {
          tab: {
            icon: 'fa-solid fa-user',
            type: 'client',
            uuid: ctx.params.uuid,
            title: 'Client'
          },
          uuid: ctx.params.uuid,
        })
      })

      page('new-client', (ctx)=>{
        this.route(ctx, 'new-client', {
          tab: {
            icon: 'fa-solid fa-user-plus',
            type: 'client',
            uuid: 1,
            title: 'New Client',
          }
        });
      })

      page('questionnaires', (ctx)=>{
        this.route(ctx, 'questionnaires', {
          tab: {
            uuid: 1,
            icon: 'playlist_add_check',
            title: 'Questionnaires'
          }
        });
      })

      page('tags', (ctx)=>{
        this.route(ctx, 'manage-tags', {
          tab: {
            uuid: 1,
            icon: 'fa-solid fa-tags',
            title: 'Tags'
          }
        });
      })

      page('case-types', (ctx)=>{
        this.route(ctx, 'case-types', {
          tab: {
            icon: 'fa-solid fa-briefcase',
            uuid: 1,
            title: 'Manage Case Types'
          },
          uuid: ctx.query.uuid || null
        })
      })

      // Resolve case to client?case
      page('case/:uuid', async (ctx, next)=>{
        try{
          let res = await harmony.get('/case', {
            uuid: ctx.params.uuid,
            token: this.store.token,
          })
          if(res.code != 200) throw res.errors;
          if(!Array.isArray(res.cases) || !res.cases.length) return next()

          page(`/client/${res.cases[0].client.uuid}?case=${res.cases[0].uuid}`)

        }catch(e){
          this.show_errors(e);
          next()
        }
      })

      page('invites', (ctx)=>{
        this.route(ctx, 'invites', {
          tab: {
            icon: 'fa-solid fa-person-circle-plus',
            uuid: 1,
            title: 'Manage Invites'
          }
        })
      })

      page('manage-users', (ctx)=>{
        this.route(ctx, 'manage-users', {
          tab: {
            icon: 'fa-solid fa-user-tie',
            uuid: 1,
            title: 'Manage Users'
          }
        })
      })

      page('unassigned-cases', (ctx)=>{
        this.route(ctx, 'unassigned-cases', {
          tab: {
            icon: 'fa-solid fa-folder-minus',
            uuid: 1,
            title: 'Unassigned Cases'
          }
        })
      })

      page('manage-groups', (ctx)=>{
        this.route(ctx, 'manage-groups', {
          tab: {
            icon: 'fa-solid fa-people-group',
            uuid: 1,
            title: 'Manage Groups'
          }
        })
      })

      page('manage-vacations', (ctx)=>{
        this.route(ctx, 'manage-vacations', {
          tab: {
            icon: 'wb_sunny',
            uuid: 1,
            title: 'Manage Vacations'
          }
        })
      })

      page('manage-expenses', (ctx)=>{
        this.route(ctx, 'manage-expenses', {
          tab: {
            icon: 'fa-solid fa-money-check-dollar',
            icon_type: 'icomoon',
            uuid: 1,
            title: 'Expense Reports'
          }
        })
      })

      page('manage-timesheets', (ctx)=>{
        this.route(ctx, 'manage-timesheets', {
          tab: {
            icon: 'assignment',
            uuid: 1,
            title: 'Manage Timesheets'
          },
          uuid: ctx.query.uuid || null
        })
      })

      page('manage-reports', (ctx)=>{
        this.route(ctx, 'manage-reports', {
          tab: {
            icon: 'fa-solid fa-clipboard-list',
            uuid: 1,
            title: 'Manage Reports'
          }
        })
      })

      page('manage-files', (ctx)=>{
        this.route(ctx, 'manage-files', {
          tab: {
            icon: 'fa-solid fa-folder-open',
            uuid: 1,
            title: 'Manage Files'
          }
        })
      })

      page('manage-accounts', (ctx)=>{
        this.route(ctx, 'chart-of-accounts', {
          tab: {
            icon: 'fa-solid fa-building-columns',
            uuid: 1,
            title: 'Manage Accounts'
          },
          uuid: ctx.query.uuid || null
        })
      })

      page('manage-products', (ctx)=>{
        this.route(ctx, 'manage-products', {
          tab: {
            icon: 'fa-solid fa-boxes-packing',
            uuid: 1,
            title: 'Manage Products'
          },
          uuid: ctx.query.uuid || null
        })
      })

      page('company-profile', (ctx)=>{
        this.route(ctx, 'company-profile', {
          tab: {
            icon: 'fa-solid fa-building',
            uuid: 1,
            title: 'Company Profile'
          },
          uuid: ctx.query.uuid || null
        })
      })

      page('manage-tax-rates', (ctx)=>{
        this.route(ctx, 'manage-tax-rates', {
          tab: {
            icon: 'fa-solid fa-money-bill-1',
            uuid: 1,
            title: 'Manage Tax Rates'
          },
          uuid: ctx.query.uuid || null
        })
      })

      page('manage-discounts', (ctx)=>{
        this.route(ctx, 'manage-discounts', {
          tab: {
            icon: 'fa-solid fa-percent',
            uuid: 1,
            title: 'Manage Discounts'
          },
          uuid: ctx.query.uuid || null
        })
      })

      page('email-campaigns', (ctx)=>{
        this.route(ctx, 'email-campaign', {
          tab: {
            icon: 'fa-solid fa-bullhorn',
            uuid: 1,
            title: 'Email Campaigns'
          },
          uuid: ctx.query.uuid || null
        })
      })

      page('forms', (ctx)=>{
        this.route(ctx, 'manage-forms', {
          tab: {
            icon: 'library_books',
            uuid: 1,
            title: 'Manage Forms'
          },
          uuid: ctx.query.uuid || null
        })
      })

      page('manage-payment-plans', (ctx)=>{
        this.route(ctx, 'manage-payment-plans', {
          tab: {
            icon: 'fa-solid fa-timeline',
            uuid: 1,
            title: 'Manage Payment Plans'
          },
          uuid: ctx.query.uuid || null
        })
      })

      page('google/connect/finish', (ctx)=>{
        this.route(ctx, 'google-connect-finish');
      })

      page('create-expense', (ctx)=>{
        this.route(ctx, 'create-expense', {
          tab: {
            icon: 'fa-solid fa-money-check-dollar',
            uuid: 1,
            title: 'Add Expense'
          }
        });
      })

      page('subscription', (ctx)=>{
        this.route(ctx, 'subscription', {
          tab: {
            icon: 'fa-solid fa-certificate',
            uuid: 1,
            title: 'Subscription'
          }
        });
      })

      page('stripe', (ctx)=>{
        this.route(ctx, 'stripe', {
          tab: {
            icon: 'fa-solid fa-credit-card',
            uuid: 1,
            title: 'Credit Card Processing'
          }
        });
      })

      page('stripe/payments/:account', (ctx)=>{
        this.route(ctx, 'stripe-payments', {
          tab: {
            icon: 'fa-solid fa-credit-card',
            title: 'Stripe Payments',
            uuid: ctx.params.account,
          },
          account: ctx.params.account,
        });
      })

      page('user-profile', (ctx)=>{
        this.route(ctx, 'user-profile', {
          tab: {
            icon: 'fa-solid fa-user',
            uuid: 1,
            title: 'User Profile'
          }
        })
      })

      page('store', (ctx)=>{
        this.route(ctx, 'store', {
          tab: {
            icon: 'fa-solid fa-store',
            uuid: 1,
            title: 'Store'
          }
        })
      })

      page('admin', (ctx)=>{
        this.route(ctx, 'admin', {
          tab: {
            icon: 'fa-solid fa-user-gear',
            type: 'admin',
            uuid: 1,
            title: 'Admin'
          }
        })
      })

      page('admin/audit-logs', (ctx)=>{
        this.route(ctx, 'audit-logs', {
          tab: {
            icon: 'fa-solid fa-binoculars',
            type: 'admin',
            uuid: 1,
            title: 'Audit Logs'
          }
        })
      })

      page('clients', (ctx)=>{
        this.route(ctx, 'client-list', {
          owes: ctx.query.owes || null,
          overdue: ctx.query.overdue || null,
          tab: {
            icon: 'fa-solid fa-users',
            uuid: 1,
            title: 'Clients'
          }
        })
      })

      page('invoice-list', (ctx)=>{
        this.route(ctx, 'invoice-list', {
          tab: {
            icon: 'fa-solid fa-file-invoice',
            uuid: 1,
            title: 'Invoices'
          }
        });
      })

      page('api-keys', (ctx)=>{
        this.route(ctx, 'api-keys', {
          tab: {
            icon: 'fa-solid fa-key',
            uuid: 1,
            title: 'API Keys'
          }
        });
      })

      /** 
       * This was set up specifically for Trix. Where we needed to store a url of a file
       * that was secure and needed a key, but we couldn't store the key or the token.
       * So we supply trix this url and when it's resolved, it will use the current token
       * to fetch the file

       * NOTE: We are not using this! clients can not do 301 redirects. Leaving here for learning.
       * This does work for clicking links in the client, but not for serving images
       */
      page('get-file/:uuid', (ctx)=>{
        if(!this.store.token) return page('/login');

        const host = document.location.hostname == 'localhost' ? 'http://localhost:3000' : 'https://api.harmonylegal.com'
        document.location.href = `${host}/file/url/${ctx.params.uuid}?redirect=true&token=${btoa(this.store.token)}`
      })

      // Super user stuff
      page('super', (ctx)=>{
        this.route(ctx, 'super', {
          tab: {
            icon: 'motorcycle',
            uuid: 1,
            title: 'Super User'
          }
        });
      })

      page('support-chat', (ctx)=>{
        this.route(ctx, 'support-chat', {
          tab: {
            icon: '',
            uuid: 1,
            title: 'Chat Support'
          }
        })
      })

      page('', (ctx)=>{
        this.route(ctx, 'dashboard', {
          tab: {
            uuid: 1,
            icon: 'fa-solid fa-house-circle-check',
            title: 'Dashboard',
            type: 'dashboard',
            closeable: false,
          }
        })
      })

      page('*', (ctx)=>{
        this.route(ctx, 'notfound');
      })

      page({});

      if(this.store.token){
        this.fetch_user()
      }

    });


  </script>

  <style>


  </style>
</app>
