import {
    AbilityBuilder,
    Ability,
} from '@casl/ability'
import {
    settings,
} from '../../router/config'

//  Read ability from localStorage
// * Handles auto fetching previous abilities if already logged in user
// ? You can update this if you store user abilities to more secure place
// ! Anyone can update localStorage so be careful and please update this
const userData = (localStorage.getItem('userData'))
const existingRole = userData ? userData.role : null

//export default new Ability(existingAbility || initialAbility) 

const {
    can,
    cannot,
    build,
    rules,
} = new AbilityBuilder(Ability);


// TODO: 修改權限設計
export const defineRulesFor = (user) => {
    user = JSON.parse(user);
    const role = user ? user.role : null;
    switch (role) {
        case 'Admin':
            can('manage', 'all');
            break;
        case 'User':
            can('read', 'all');
            can('upload','blog')
            cannot('read', 'permission');
            cannot('read', '模板');
            cannot('read', '管理功能');
            break;
        case 'Trainer':
            break;
        default:
            cannot('manage', 'all');
            can("read", 'Blog');
            settings.routes.forEach(route => {
                let requiresAuth = route && route.meta && route.meta.requiresAuth ? route.meta.requiresAuth : false;
                if (route.name != undefined && !requiresAuth) {
                    can("read", route.name)
                }
            })
            break;
    };
    return rules
}

defineRulesFor(userData);
export default build();
