import os
import shutil

from flask import send_from_directory
from flask_restful import Resource, abort

from PDMI.models import Modules


class ApiIndex(Resource):
    def get(self):
        return {
            "api version": "0.0.1"
        }


class ApiModuleList(Resource):
    def get(self):
        modules = Modules.query.filter().all()
        return {module.name: [version.version for version in module.versions] for module in modules}


class ApiModuleVersions(Resource):
    def get(self, module):
        module = Modules.query.filter_by(name=module).first_or_404()
        return {"versions": [version.version for version in module.versions]}


class ApiModuleGet(Resource):
    def get(self, module, version):
        module = Modules.query.filter_by(name=module).first_or_404()
        versions = [version.version for version in module.versions]
        if version not in versions:
            abort(404)
        print(os.getcwd())
        if not os.path.exists(os.path.join("PDMI", "modules", module.name, version + ".zip")):
            shutil.make_archive(os.path.join("PDMI", "modules", module.name, version), 'zip',
                                os.path.join("PDMI", "modules", module.name, version))
        return send_from_directory(
            os.path.join("modules", module.name, ),
            version + ".zip"
        )
