// file-downloader.service.ts

import { Injectable } from '@angular/core';
import * as Encoding from 'encoding-japanese';

@Injectable({
  providedIn: 'root',
})
export class FileDownloaderService {
  static FileDownload(base64: string, FileName: string): void {
    FileName = FileName.trim();
    
    if (base64 !== undefined && base64 !== null) {
      let fileType = 'text/plain'; // デフォルトのMIMEタイプ
      let blobData;


      const parts = FileName.split('.');

      const extension = parts[parts.length - 1];//ileName.split('.').pop().toLowerCase();
      const mimeTypes = {
        csv: 'text/csv',
        txt: 'text/plain',
        png: 'image/png',
        jpg: 'image/jpeg',
        jpeg: 'image/jpeg',
        zip: 'application/zip',
        pdf: 'application/pdf',
        xlsx: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
        docx: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
      };

      fileType = mimeTypes[extension] || 'text/plain';

      try {
        switch (extension) {
          case 'csv':
            // 文字コード変換をShift-JISへ
            blobData = this.convertToShiftJIS(base64);
            break;
          case 'txt':
            blobData = this.convertToUnicode(base64);
            break;
          case 'png':
          case 'jpg':
          case 'jpeg':
          case 'zip':
          case 'pdf':
          case 'xlsx':
          case 'docx':
            blobData = this.base64ToUint8Array(base64);
            break;
          default:
            alert('サポートされていないタイプのファイルです。');
            return;
        }

        const blob = new Blob([blobData], { type: fileType });

        if (blob.size !== 0) {
          const downloadLink = document.createElement('a');
          const linkSource = window.URL.createObjectURL(blob);

          downloadLink.href = linkSource;
          downloadLink.download = FileName;
          downloadLink.click();
          window.URL.revokeObjectURL(linkSource);
        }
      } catch (error) {
        console.error('Error during file download:', error);
      }
    }
  }

  private static base64ToUint8Array(base64: string): Uint8Array {
    const binaryString = window.atob(base64);
    const len = binaryString.length;
    const bytes = new Uint8Array(len);
    for (let i = 0; i < len; i++) {
      bytes[i] = binaryString.charCodeAt(i);
    }
    return bytes;
  }

  private static convertToShiftJIS(base64: string): Uint8Array {
    const unicodeList = [];
    for (let i = 0; i < base64.length; i++) {
      unicodeList.push(base64.charCodeAt(i));
    }
    const shiftJisCodeList = Encoding.convert(unicodeList, { from: 'UNICODE', to: 'SJIS' });
    return new Uint8Array(shiftJisCodeList);
  }

  private static convertToUnicode(base64: string): Uint8Array {
    const unicodeList = [];
    for (let i = 0; i < base64.length; i++) {
      unicodeList.push(base64.charCodeAt(i));
    }
    return new Uint8Array(unicodeList);
  }
}
