<?php

namespace RxConnexionBundle\Controller;

use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Firebase\JWT\JWT;

use RxConnexionBundle\Entity\GeneralUserEntity;

/**
 * @Route("/api")
 */
class ApiController extends Controller
{
    public function health_facility_type_listAction(Request $request) {

        $response = array('success' => 0, 'errorMessage' => '', 'healthFacilityTypes' => array());

        $params = json_decode($request->getContent(), true);

        $requestedAt = $params['requestedAt'];
        $hash = $params['hash'];

        if(md5($requestedAt) !== $hash) {
            //$response['errorMessage'] = 'Invalid hash.';
        }

        if(empty($response['errorMessage'])) {

            $em = $this->em();

            $healthFacilityTypes = $em->getRepository('RxConnexionBundle:HealthFacilityTypeEntity')->findAll();

            $response['healthFacilityTypes'][] = array(
                'value' => 'all',
                'description' => 'All Types'
            );

            foreach($healthFacilityTypes as $healthFacilityType) {
                $response['healthFacilityTypes'][] = array(
                    'value' => $healthFacilityType->getId(),
                    'description' => $healthFacilityType->getDescription()
                );
            }

            $response['success'] = 1;
        }

        return new JsonResponse($response);
    }

    public function health_facility_listAction(Request $request) {

        $response = array('success' => 0, 'errorMessage' => '', 'healthFacilities' => array());

        /*
        $params = json_decode($request->getContent(), true);

        $healthFacilityType = $params['healthFacilityType'];
        $searchQuery = $params['searchQuery'];
        $clinicNameQuery = $params['clinicNameQuery'];
        $addressQuery = $params['addressQuery'];
        $cityQuery = $params['cityQuery'];
        $provinceQuery = $params['provinceQuery'];
        $requestedAt = $params['requestedAt'];
        $hash = $params['hash'];
        */

        $params = array(
            'hasAccountOnly' => $request->query->get('hasAccountOnly'),
            'healthFacilityType' => $request->query->get('healthFacilityType'),
            'searchQuery' => $request->query->get('searchQuery'),
            'clinicNameQuery' => $request->query->get('clinicNameQuery'),
            'addressQuery' => $request->query->get('addressQuery'),
            'cityQuery' => $request->query->get('cityQuery'),
            'provinceQuery' => $request->query->get('provinceQuery'),
            'requestedAt' => $request->query->get('requestedAt'),
            'hash' => $request->query->get('hash')
        );

        $localHash = md5($params['hasAccountOnly'] . $params['healthFacilityType'] . $params['searchQuery'] . $params['clinicNameQuery'] . $params['addressQuery'] . $params['cityQuery'] . $params['provinceQuery'] . $params['requestedAt'] . 'zapconexion!23');

        if($localHash !== $params['hash']) {
            $response['errorMessage'] = 'Invalid hash. ' . $localHash . ' ! ' . $params['hash'];
        }

        if(empty($response['errorMessage'])) {

            $em = $this->em();

            //$healthFacilities = $em->getRepository('RxConnexionBundle:HealthFacilityEntity')->getWithParams($params);
            $healthFacilities = $em->getRepository('RxConnexionBundle:HealthFacilityEntity')->apiList($params);

            foreach($healthFacilities as $healthFacility) {

                $contacts = array(
                    'mobileNumbers' => array(),
                    'phoneNumbers' => array()
                );

                if(!empty($healthFacility['mobileNo'])) $contacts['mobileNumbers'][] = $healthFacility['mobileNo'];
                if(!empty($healthFacility['mobileNoTwo'])) $contacts['mobileNumbers'][] = $healthFacility['mobileNoTwo'];
                if(!empty($healthFacility['mobileNoThree'])) $contacts['mobileNumbers'][] = $healthFacility['mobileNoThree'];
                if(!empty($healthFacility['phoneNo'])) $contacts['phoneNumbers'][] = $healthFacility['phoneNo'];
                if(!empty($healthFacility['phoneNoTwo'])) $contacts['phoneNumbers'][] = $healthFacility['phoneNoTwo'];
                if(!empty($healthFacility['phoneNoThree'])) $contacts['phoneNumbers'][] = $healthFacility['phoneNoThree'];

                $response['healthFacilities'][] = array(
                    'hasAccount' => $healthFacility['accountId'] ? true : false,
                    'typeName' => $healthFacility['healthFacilityType_description'],
                    'companyName' => $healthFacility['companyDescription'],
                    'clinicName' => $healthFacility['description'],
                    'address' => $healthFacility['address'],
                    'cityName' => $healthFacility['city_description'],
                    'provinceName' => $healthFacility['province_description'],
                    'geoLocation' => array(
                        'lat' => $healthFacility['geoLatitude'],
                        'long' => $healthFacility['geoLongitude']
                    ),
                    'contacts' => $contacts
                );
            }

            $response['success'] = 1;
        }

        return new JsonResponse($response);
    }

    public function health_facility_list_v2Action(Request $request) {

        $response = array('success' => false);

        $params = json_decode($request->getContent(), true);
        $searchDetails = json_decode($params['searchDetails'], true);

        $localHash = md5($params['requestTime'] . $searchDetails['type'] . $searchDetails['keyWords'] . $this->container->getParameter('api_secret'));

        if($localHash !== $params['hash']) {

            $response['errorMessages'] = array('Something went wrong. Please try again.');

        } else {

            $response['healthFacilities'] = array();

            $em = $this->em();
            $healthFacilities = $em->getRepository('RxConnexionBundle:HealthFacilityEntity')->apiList_v2($searchDetails);

            foreach($healthFacilities as $healthFacility) {

                $contacts = array(
                    'mobileNumbers' => array(),
                    'phoneNumbers' => array()
                );

                if(!empty($healthFacility['mobileNo'])) $contacts['mobileNumbers'][] = $healthFacility['mobileNo'];
                if(!empty($healthFacility['mobileNoTwo'])) $contacts['mobileNumbers'][] = $healthFacility['mobileNoTwo'];
                if(!empty($healthFacility['mobileNoThree'])) $contacts['mobileNumbers'][] = $healthFacility['mobileNoThree'];
                if(!empty($healthFacility['phoneNo'])) $contacts['phoneNumbers'][] = $healthFacility['phoneNo'];
                if(!empty($healthFacility['phoneNoTwo'])) $contacts['phoneNumbers'][] = $healthFacility['phoneNoTwo'];
                if(!empty($healthFacility['phoneNoThree'])) $contacts['phoneNumbers'][] = $healthFacility['phoneNoThree'];

                $response['healthFacilities'][] = array(
                    'hasAccount' => $healthFacility['accountId'] ? true : false,
                    'typeName' => $healthFacility['healthFacilityType_description'],
                    'companyName' => $healthFacility['companyDescription'],
                    'clinicName' => $healthFacility['description'],
                    'address' => $healthFacility['address'],
                    'cityName' => $healthFacility['city_description'],
                    'provinceName' => $healthFacility['province_description'],
                    'geoLocation' => array(
                        'lat' => $healthFacility['geoLatitude'],
                        'long' => $healthFacility['geoLongitude']
                    ),
                    'contacts' => $contacts
                );
            }

            $response['success'] = true;
        }

        return new JsonResponse($response);
    }

    public function general_user_registerAction(Request $request) {

        $result = array('success' => false);
        $data = json_decode($request->getContent(), true);
        $localHash = md5($data['registrationInfo']['username'] .
            $data['registrationInfo']['password']['first'] .
            $data['registrationInfo']['password']['second'] .
            $data['registrationInfo']['firstName'] .
            $data['registrationInfo']['middleName'] .
            $data['registrationInfo']['lastName'] .
            $data['registrationInfo']['gender'] .
            $data['registrationInfo']['birthDate']['month'] .
            $data['registrationInfo']['birthDate']['day'] .
            $data['registrationInfo']['birthDate']['year'] .
            $data['registrationInfo']['mobileNo'] .
            $data['registrationInfo']['phoneNo'] .
            $data['registrationInfo']['email'] .
            'zapconexion.123!');

        if($data['hash'] !== $localHash) {
            $result['errorMessages'] = array('Request invalid, Please try again.');
        } else {

            if (!empty($data['registrationInfo']['birthDate']['month']) && !empty($data['registrationInfo']['birthDate']['day']) && !empty($data['registrationInfo']['birthDate']['year'])) {
                $birthDate = $data['registrationInfo']['birthDate']['month'] . '/' . $data['registrationInfo']['birthDate']['day'] . '/' . $data['registrationInfo']['birthDate']['year'];
            } else {
                $birthDate = '';
            }

            $generalUser_form = array(
                'isFromApi' => true,
                'action' => 'n',
                'id' => 0,
                'username' => $data['registrationInfo']['username'],
                'password' => array(
                    'first' => $data['registrationInfo']['password']['first'],
                    'second' => $data['registrationInfo']['password']['second']
                ),
                'first_name' => $data['registrationInfo']['firstName'],
                'last_name' => $data['registrationInfo']['lastName'],
                'gender' => $data['registrationInfo']['gender'],
                'birth_date' => $birthDate,
                'email' => $data['registrationInfo']['email'],
                'email_two' => '',
                'email_three' => ''
            );

            $em = $this->em();
            $errors = $em->getRepository('RxConnexionBundle:GeneralUserEntity')->validate($generalUser_form);

            if (count($errors)) {
                $result['errorMessages'] = $errors;
            } else {

                $newGeneralUser = new GeneralUserEntity();
                $newGeneralUser->setUsername($data['registrationInfo']['username']);
                $newGeneralUser->setPassword($data['registrationInfo']['password']['first']);
                $newGeneralUser->setFirstName($data['registrationInfo']['firstName']);
                $newGeneralUser->setMiddleName($data['registrationInfo']['middleName']);
                $newGeneralUser->setLastName($data['registrationInfo']['lastName']);
                $newGeneralUser->setGender($data['registrationInfo']['gender']);
                $newGeneralUser->setBirthDate($birthDate);
                $newGeneralUser->setMobileNo($data['registrationInfo']['mobileNo']);
                $newGeneralUser->setPhoneNo($data['registrationInfo']['phoneNo']);
                $newGeneralUser->setEmail($data['registrationInfo']['email']);
                $em->persist($newGeneralUser);
                $em->flush();

                $result['success'] = true;
                $result['successMessage'] = 'You have successfully registered.';
            }
        }

        return new JsonResponse($result);
    }

    public function general_user_register_v2Action(Request $request) {

        $result = array('success' => false);

        $data = json_decode($request->getContent(), true);
        $data['registrationInfo'] = json_decode($data['registrationInfo'], true);

        $localHash = md5($data['requestTime'] .
            $data['registrationInfo']['username'] .
            $data['registrationInfo']['password']['first'] .
            $data['registrationInfo']['password']['second'] .
            $data['registrationInfo']['firstName'] .
            $data['registrationInfo']['middleName'] .
            $data['registrationInfo']['lastName'] .
            $data['registrationInfo']['gender'] .
            $data['registrationInfo']['birthDate'] .
            $data['registrationInfo']['mobileNo'] .
            $data['registrationInfo']['phoneNo'] .
            $data['registrationInfo']['email'] .
            $this->container->getParameter('api_secret'));

        if($data['hash'] !== $localHash) {

            $result['errorMessages'] = array('Something went wrong. Please try again');

        } else {

            $generalUser_form = array(
                'isFromApi' => true,
                'action' => 'n',
                'id' => 0,
                'username' => $data['registrationInfo']['username'],
                'password' => array(
                    'first' => $data['registrationInfo']['password']['first'],
                    'second' => $data['registrationInfo']['password']['second']
                ),
                'first_name' => $data['registrationInfo']['firstName'],
                'last_name' => $data['registrationInfo']['lastName'],
                'gender' => $data['registrationInfo']['gender'],
                'birth_date' => $data['registrationInfo']['birthDate'],
                'email' => $data['registrationInfo']['email'],
                'email_two' => '',
                'email_three' => ''
            );

            $em = $this->em();
            $errors = $em->getRepository('RxConnexionBundle:GeneralUserEntity')->validate($generalUser_form);

            if (count($errors)) {
                $result['errorMessages'] = $errors;
            } else {

                $newGeneralUser = new GeneralUserEntity();
                $newGeneralUser->setUsername($data['registrationInfo']['username']);
                $newGeneralUser->setPassword($data['registrationInfo']['password']['first']);
                $newGeneralUser->setFirstName($data['registrationInfo']['firstName']);
                $newGeneralUser->setMiddleName($data['registrationInfo']['middleName']);
                $newGeneralUser->setLastName($data['registrationInfo']['lastName']);
                $newGeneralUser->setGender($data['registrationInfo']['gender']);
                $newGeneralUser->setBirthDate($data['registrationInfo']['birthDate']);
                $newGeneralUser->setMobileNo($data['registrationInfo']['mobileNo']);
                $newGeneralUser->setPhoneNo($data['registrationInfo']['phoneNo']);
                $newGeneralUser->setEmail($data['registrationInfo']['email']);
                $em->persist($newGeneralUser);
                $em->flush();

                $result['success'] = true;
                $result['successMessage'] = 'You have successfully registered.';
            }
        }

        return new JsonResponse($result);
    }

    /**
     * @Route("/api-general-user-login", name="api_general_user_login")
     */
    public function general_user_loginAction(Request $request) {

        $result = array('success' => false);
        $data = json_decode($request->getContent(), true);
        $localHash = md5($data['loginCredentials']['username'] . $data['loginCredentials']['password'] . 'zapconexion.123!');

        if($data['hash'] !== $localHash) {
            $result['errorMessages'] = array('Request invalid, Please try again.');
        } else {

            $em = $this->em();
            $generalUser = $em->getRepository('RxConnexionBundle:GeneralUserEntity')->findOneBy(array('username' => $data['loginCredentials']['username'], 'password' => md5($data['loginCredentials']['password'])));

            if($generalUser) {

                if($this->isLoggedInGeneralUser()) {
                    $result['errorMessages'] = array('You have logged in already.');
                } else {

                    $session = $this->get('session');
                    $session->clear();

                    $generalUserData = array(
                        'id' => $generalUser->getId(),
                        'username' => $generalUser->getUsername(),
                        'firstName' => $generalUser->getFirstName(),
                        'middleName' => $generalUser->getMiddleName(),
                        'fullName' => $generalUser->getFullName()
                    );

                    $session->set('generalUserData', $generalUserData);

                    $result['success'] = true;
                    $result['generalUserData'] = $generalUserData;
                }

            } else {
                $result['errorMessages'] = array('Invalid login information.');
            }
        }

        return new JsonResponse($result);
    }

    public function general_user_login_v2Action(Request $request) {

        $result = array('success' => false);
        $data = json_decode($request->getContent(), true);
        $localHash = md5($data['requestTime'] .
            $data['username'] .
            $data['password'] .
            $this->container->getParameter('api_secret'));

        if($data['hash'] !== $localHash) {
            $result['errorMessages'] = array('Something went wrong. Please try again.');
        } else {

            $em = $this->em();
            $generalUser = $em->getRepository('RxConnexionBundle:GeneralUserEntity')->findOneBy(array('username' => $data['username'], 'password' => $data['password']));

            if($generalUser) {

                $generalUserData = array(
                    'id' => $generalUser->getId(),
                    'username' => $generalUser->getUsername(),
                    'firstName' => $generalUser->getFirstName(),
                    'middleName' => $generalUser->getMiddleName(),
                    'fullName' => $generalUser->getFullName()
                );

                $result['success'] = true;
                $result['userData'] = $generalUserData;

            } else {
                $result['errorMessages'] = array('Invalid login information.');
            }
        }

        return new JsonResponse($result);
    }

    public function general_user_is_logged_inAction(Request $request) {

        $result['success'] = false;
        $params = $request->query->all();
        $localHash = md5($params['generalUserData'] . 'zapconexion.123');

        if($params['hash'] === $localHash) {
            $result['success'] = $this->isLoggedInGeneralUser();
        }

        return new JsonResponse($result);
    }

    public function general_user_logoutAction(Request $request) {

        $result['success'] = false;
        $data = json_decode($request->getContent(), true);
        $localHash = md5($data['generalUserData'] . 'zapconexion.123');

        if($data['hash'] === $localHash) {
            $session = $this->get('session');
            $session->clear();
            $result['success'] = true;
        }

        return new JsonResponse($result);
    }

    /**
     * @Route("/db-dump/latest-file", name="api_db_dump_latest_file")
     */
    public function db_dump_latest_fileAction(Request $request)
    {
        header('Access-Control-Allow-Origin: *');
        header('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS');

        $logData = '[' . date('Y-m-d H:i:s') . ']';

        $auth = explode(' ', $request->headers->get('Authorization'));

        if(isset($auth[0]) && 'Bearer' === $auth[0] && isset($auth[1])) {

            try {
                $payload = (array) JWT::decode($auth[1], $this->getParameter('jwt_key'), array($this->getParameter('jwt_alg')));
            } catch(\Exception $e) {
                $payload = null;
            }

            $postData = json_decode($request->getContent(), true);

            $logData .= ' Payload: ' . json_encode($payload);
            $logData .= ' Post Data: ' . json_encode($postData);

            if(isset($payload['reqTime'])) {

                if(time() / $payload['reqTime'] <= 30) {

                    $dbDumpDir = $this->getParameter('db_dump_dir');
                    $dbDumpNamePrefix = $this->getParameter('db_dump_name_prefix');

                    $files = array_diff(scandir($dbDumpDir), array('.', '..'));

                    if(count($files)) {

                        $fileName = null;
                        $ctime = null;

                        // Get the latest file
                        foreach($files as $fname) {
                            if(FALSE === stripos($fname, $dbDumpNamePrefix)) {
                                continue;
                            }
                            $fileName = $fname;
                            $fctime = filectime($dbDumpDir . '/' . $fname);
                            if(null === $ctime || $fctime > $ctime) {
                                $ctime = $fctime;
                            }
                        }

                        if(null !== $fileName) {
                            $result = array(
                                'success' => true,
                                'fName' => $fileName,
                                'dlName' => str_replace($dbDumpNamePrefix, $this->getParameter('db_dump_dl_prefix'), $fileName)
                            );
                        } else {
                            $result = array('success' => false, 'msg' => 'No available db dump.');
                        }
                    } else {
                        $result = array('success' => false, 'msg' => 'No available db dump.');
                    }
                } else {
                    $result = array('success' => false, 'msg' => 'Invalid request data.');
                }
            } else {
                $result = array('success' => false, 'msg' => 'Invalid request data.');
            }
        } else {
            $result = array('success' => false, 'msg' => 'Invalid request.');
        }

        $logData .= ' Response: ' . json_encode($result) . ' [' . date('Y-m-d H:i:s') . ']';

        $this->appendLogs('db-dump-latest-file', 'db-dump/latest-file', $logData);

        return new JsonResponse($result);
    }

    /**
     * @Route("/db-dump/do-download", name="api_db_dump_do_download")
     */
    public function db_dump_do_downloadAction(Request $request)
    {
        header('Access-Control-Allow-Origin: *');
        header('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS');

        $logData = '[' . date('Y-m-d H:i:s') . ']';

        $auth = explode(' ', $request->headers->get('Authorization'));

        if(isset($auth[0]) && 'Bearer' === $auth[0] && isset($auth[1])) {

            try {
                $payload = (array) JWT::decode($auth[1], $this->getParameter('jwt_key'), array($this->getParameter('jwt_alg')));
            } catch(\Exception $e) {
                $payload = null;
            }

            $postData = json_decode($request->getContent(), true);

            $logData .= ' Payload: ' . json_encode($payload);
            $logData .= ' Post Data: ' . json_encode($postData);

            if(isset($payload['reqTime']) && isset($payload['fName'])) {

                if(time() / $payload['reqTime'] <= 30) {

                    $filePath = $this->getParameter('db_dump_dir') . '/' . $payload['fName'];
                    $handle = fopen($filePath, 'rb');

                    if(FALSE !== $handle) {

                        $logData .= ' Response: ' . json_encode(array('success' => true, 'msg' => 'DB dump download started...')) . ' [' . date('Y-m-d H:i:s') . ']';
                        $this->appendLogs('db-dump-do-download', 'db-dump/do-download', $logData);

                        $dbDumpNamePrefix = $this->getParameter('db_dump_name_prefix');
                        $dlName = str_replace($dbDumpNamePrefix, $this->getParameter('db_dump_dl_prefix'), $payload['fName']);

                        header("Pragma: public");
                        header('Content-Disposition: attachment; filename="' . $dlName . '"');
                        header('Expires: 0');
                        header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
                        header("Content-Transfer-Encoding: binary");
                        header("Content-Type: " . mime_content_type($filePath));
                        header("Content-Length: " . filesize($filePath));
                        ob_clean();

                        $chunkSize = 1024 * 1024;
                        while (!feof($handle)) {
                            $buffer = fread($handle, $chunkSize);
                            echo $buffer;
                            ob_flush();
                            flush();
                        }

                        fclose($handle);

                        exit;

                    } else {
                        $result = array('success' => false, 'msg' => 'DB dump not found.');
                    }
                } else {
                    $result = array('success' => false, 'msg' => 'Invalid request data.');
                }
            } else {
                $result = array('success' => false, 'msg' => 'Invalid request data.');
            }
        } else {
            $result = array('success' => false, 'msg' => 'Invalid request.');
        }

        $logData .= ' Response: ' . json_encode($result) . ' [' . date('Y-m-d H:i:s') . ']';

            $this->appendLogs('db-dump-do-download', 'db-dump/do-download', $logData);

        return new JsonResponse($result);
    }

    /** FOR HR PORTAL OF RX-CONEXION */

    //LOGIN FOR HR PORTAL
//    /**
//     * @Route("/hr_portal_login", name="api_hr_portal_login")
//     */
//    public function hr_portal_login_Action(Request $request) {
//
//        header('Access-Control-Allow-Headers: *');
//        header('Access-Control-Allow-Origin: *');
//        header('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS');
//
//        $logData = '[' . date('Y-m-d H:i:s') . ']';
//
//        $auth = explode(' ', $request->headers->get('Authorization'));
//
//        if(isset($auth[0]) && 'Bearer' === $auth[0] && isset($auth[1])) {
//
//            try {
//                $payload = (array) JWT::decode($auth[1], $this->getParameter('jwt_key'), array($this->getParameter('jwt_alg')));
//            } catch(\Exception $e) {
//                $payload = null;
//            }
//
//            $postData = json_decode($request->getContent(), true);
//
//            $logData .= ' Payload: ' . json_encode($payload);
//            $logData .= ' Post Data: ' . json_encode($postData);
//
//            $em = $this->getDoctrine()->getManager();
//            $users = $em->getRepository('RxConnexionBundle:AccountUserEntity')->findAll();
//
//            $result['userList'] = $users;
//            $result['success'] = true;
//
//
//        } else {
//            $result = array('success' => false, 'msg' => 'Invalid connection. Please contact the app developer.');
//        }
//
//        $logData .= ' Response: ' . json_encode($result) . ' [' . date('Y-m-d H:i:s') . ']';
//
//        $this->appendLogs('login', 'login', $logData);
//
//        return new JsonResponse($result);
//    }

    /**
     * @Route("/hr_portal_login", name="api_hr_portal_login")
     */
    public function hr_portal_loginAction(Request $request) {

        $result = array('success' => false);
        $data = json_decode($request->getContent(), true);

        $em = $this->getDoctrine()->getManager();
        $users = $em->getRepository('RxConnexionBundle:AccountUserEntity')->findAll();

        $hrUsers = array();
        foreach ($users as $user) {
            $hrUsers[] = array(
              'username' => $users->getUser()
            );
        }

        return new JsonResponse($result);
    }

    // Private Functions

    private function appendLogs($logName, $logPath, $logData) {

        $logAbsPath = $this->getParameter('api_log_dir') . '/' . $logPath;
        $logFilename = $logAbsPath . '/' . $logName . '.log';

        if(file_exists($logAbsPath)) {
            if (file_exists($logFilename)) {
                $logFile = fopen($logFilename, "a+");
                fwrite($logFile, PHP_EOL . $logData);
            } else {
                $logFile = fopen($logFilename, "w");
                fwrite($logFile, $logData);
            }
            fclose($logFile);

            $logSize = filesize($logFilename);
            if($logSize >= $this->getParameter('api_log_max_size')) {
                rename($logFilename, $logAbsPath . '/' . $logName . '-' . date('Y-m-d-H-i-s') . '.log');
            }
        }
    }
}
