from snek.system.view import BaseView
from aiohttp import web

class DriveView(BaseView):

    login_required = True

    async def get(self):

        drive_uid = self.request.match_info.get("drive")

        if drive_uid:
            drive = await self.services.drive.get(uid=drive_uid)
            drive_items = []
            async for item in drive.items:
                record = item.record
                record['url'] = '/drive.bin/' + record['uid'] + '.' + item.extension
                drive_items.append(record)
            return web.json_response(drive_items)

        user = await self.services.user.get(uid=self.session.get("uid"))

        
        drives = []
        async for drive in self.services.drive.get_by_user(user['uid']):
            record = drive.record
            record['items'] = []
            async for item in drive.items:
                drive_item_record = item.record
                drive_item_record['url'] = '/drive.bin/' + drive_item_record['uid'] + '.' + item.extension
                record['items'].append(item.record)
            drives.append(record)
        
        return web.json_response(drives)
