import Immutable from 'immutable';
import _ from 'lodash';
import Url from 'lib/Url';

import UserStore from 'stores/Users';
import ConfigStore from 'stores/Config';

const DEFAULTS = {
    id: undefined,
    login: undefined,
    display_name: undefined,
    avatar_id: undefined,
    internal: undefined,
    sids: undefined,
    locale: undefined,
    org_id: undefined,
    country: undefined,
};

class Session extends Immutable.Record(DEFAULTS) {
    static PRIMARY_KEY = 'id';
    static TYPE_NAME = 'session';

    static create(data) {
        const nextData = _.pick(data, Object.keys(DEFAULTS));

        return new Session(Immutable.fromJS(nextData));
    }

    getId() {
        return this.get(Session.PRIMARY_KEY);
    }

    getType() {
        return Session.TYPE_NAME;
    }

    equals(x) {
        return (x instanceof Session) && x.getId() === this.getId();
    }

    getName() {
        return this.get('display_name');
    }

    getUser() {
        return UserStore.get(this.getId());
    }

    getLogin() {
        return this.get('login');
    }

    getLocale() {
        return this.get('locale');
    }

    getOrgIds() {
        return this.get('org_id');
    }

    getFirstOrgId() {
        const orgIds = this.getOrgIds() || '';

        return orgIds.split(',')[0];
    }

    isInternal() {
        return this.get('internal');
    }

    getAvatar(size = 200) {
        return Url.build(ConfigStore.get('ui.avatar.url'), {
            id: this.get('avatar_id') || '0',
            size,
        });
    }
}

export default Session;
