﻿using System;
/* Google Drive Apis */
using Google.Apis.Drive.v3;
using Google.Apis.Services;
using Google.Apis.Auth.OAuth2;
using System.Threading;
using Google.Apis.Util.Store;
using Google.Apis.Download;
using System.IO;

namespace MUL
{
    class google_drive_api_class
    {
        /* 싱글톤 패턴 */
        private static google_drive_api_class _instance;
        public static google_drive_api_class Instance()
        {
            if (_instance == null)
                _instance = new google_drive_api_class();
            return _instance;
        }
        /* 클래스 정의 */
        private DriveService _service;
        string[] scopes = new string[] { DriveService.Scope.Drive,
                                 DriveService.Scope.DriveFile};
        private void get_Permission()
        {
            // @clientId 수정 필요함
            var clientId = "@id";
            // @clientSecret 수정 필요함
            var clientSecret = "@secret";
            var credential = GoogleWebAuthorizationBroker.AuthorizeAsync(new ClientSecrets
            {
                ClientId = clientId,
                ClientSecret = clientSecret
            },
                scopes,
                Environment.UserName,
                CancellationToken.None,
                new FileDataStore("Daimto.GoogleDrive.Auth.Store")).Result;

            // Create Drive API service.
            _service = new DriveService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName = "MUL",
            });
        }
        private Google.Apis.Drive.v3.Data.File get_GoogleDriveFile(string fileName) {
            if (_service == null)
                get_Permission();

            var FileListResult = _service.Files.List().Execute();

            foreach (Google.Apis.Drive.v3.Data.File file in FileListResult.Files) {
                if (fileName.CompareTo(file.Name) == 0)
                    return file;
            }
            return null;
        }
        /* 구글드라이브 공유링크 파일을 다운로드 받는 API */
        public void download_GoogleDriveURL(string fileName, string saveFilePath)
        {
            Google.Apis.Drive.v3.Data.File downloadFile = get_GoogleDriveFile(fileName);
            try {
                var fileId = downloadFile.Id;
                var request = _service.Files.Get(fileId);
                var ms = new System.IO.MemoryStream();

                request.MediaDownloader.ProgressChanged +=
                    (IDownloadProgress progress) =>
                    {
                        switch (progress.Status)
                        {
                            case DownloadStatus.Downloading:
                                {
                                    Console.WriteLine(progress.BytesDownloaded);
                                    break;
                                }
                            case DownloadStatus.Completed:
                                {
                                    Console.WriteLine("Download complete.");
                                    break;
                                }
                            case DownloadStatus.Failed:
                                {
                                    Console.WriteLine("Download failed.");
                                    break;
                                }
                        }
                    };
                request.Download(ms);
                /* Memorystream save to file */
                string path_download_file = saveFilePath + "\\" + downloadFile.Name;
                FileStream file = new FileStream(path_download_file, FileMode.Create, FileAccess.Write);
                ms.WriteTo(file);
                file.Close();
                ms.Close();
            } catch (Exception e) {
                Console.WriteLine(e);
            }
        }
    }
}
