package
{
    import flash.display.Sprite;
    import flash.display.Shape;
    import flash.events.Event;
    import zip.ZIPResourceLoader;
	import zip.ZIPClientLoader;
    import flash.events.ProgressEvent;
	import flash.text.TextField;
    import flash.text.TextFormat;

    public class ProgressBar extends Sprite
    {
        public var progressBar:Shape;
        private var backgroundBar:Shape;
        public var progress:Number;
        private var maxWidth:Number;
        private var maxHeight:Number;
        public var resourceLoader:ZIPResourceLoader;
		public var clientLoader:ZIPClientLoader;
        private var bytesLoaded:Number;
        private var bytesTotal:Number;
		private var direction:int = 1; // Направление анимации (1 - вперед, -1 - назад)
        private var animationSpeed:Number = 0.01; // Скорость анимации прогресс-бара
		private var rectangle:Shape = new Shape();
		public var progressText:TextField;

        public function ProgressBar()
        {
            init();
        }

        public function setClientLoader(clientLoader:ZIPClientLoader):void 
		{
            clientLoader.addEventListener(ProgressEvent.PROGRESS, onProgressUpdate);
        }
		
        public function setResourceLoader(resourceLoader:ZIPResourceLoader):void 
		{
            resourceLoader.addEventListener(ProgressEvent.PROGRESS, onProgressUpdate);
        }

        public function onProgressUpdate(event:ProgressEvent):void 
		{
            progress = event.bytesLoaded / event.bytesTotal;
            updateProgressBar();
        }

        private function init():void
        {
			clientLoader = new ZIPClientLoader(this);
	        //resourceLoader = new ZIPResourceLoader(this);
            maxWidth = 700;
            maxHeight = 28;
            progress = 0;

            backgroundBar = new Shape();
            backgroundBar.graphics.beginFill(0x014ca3);
			 var cornerRadius:Number = 10;
            backgroundBar.graphics.drawRoundRect(0, 0, maxWidth, maxHeight, cornerRadius);
			        
            backgroundBar.graphics.endFill();

            progressBar = new Shape();
            progressBar.visible = false;
			
            addChild(backgroundBar);
            addChild(progressBar);
			
            progressText = new TextField();
            progressText.width = maxWidth;
            progressText.height = maxHeight;
            progressText.text = "Скачивание файлов...";
            var textFormat:TextFormat = new TextFormat("_sans", 18, 0x348aee);
            textFormat.align = "center";
            progressText.y = maxHeight + 10;
            progressText.defaultTextFormat = textFormat;
            addChild(progressText);
            progressText.visible = false;
			
            addEventListener(Event.ADDED_TO_STAGE, onAddedToStage);
            addEventListener(Event.REMOVED_FROM_STAGE, onRemovedFromStage);
        }
		
        public function incilizationProgressBar():void
        {
             // Обновление параметров размеров прогресс-бара
            maxWidth = 54;
            maxHeight = 34;
            var cornerRadius:Number = 5;
            var yOffset:Number = -3; // смещение по вертикали на 2 пикселя
    
            // Создание прямоугольника
            var rectangle:Shape = new Shape();
            rectangle.graphics.beginFill(0x348aee);
            rectangle.graphics.drawRoundRect(0, yOffset, maxWidth, maxHeight, cornerRadius, cornerRadius);
            rectangle.graphics.endFill();
    
            addChild(rectangle);

           var direction:int = 1; // Направление анимации (1 - вперед, -1 - назад)
           var speed:Number = 7; // Скорость анимации (пиксели за шаг)
           var targetX:Number = 650; // Конечная позиция прямоугольника

           addEventListener(Event.ENTER_FRAME, incilizationAnimateProgressBar);

           function incilizationAnimateProgressBar(event:Event):void
           {
                rectangle.x += direction * speed;
        
                if (rectangle.x >= targetX || rectangle.x <= 0)
                {
                    direction *= -1; // Переключение направления анимации
                }
           }
        }
		
        private function onAddedToStage(event:Event):void
        {
            removeEventListener(Event.ADDED_TO_STAGE, onAddedToStage);
            addEventListener(Event.ENTER_FRAME, onUpdate);
        }

        private function onRemovedFromStage(event:Event):void
        {
            removeEventListener(Event.REMOVED_FROM_STAGE, onRemovedFromStage);
            removeEventListener(Event.ENTER_FRAME, onUpdate);
        }

        private function onUpdate(event:Event):void
        {
          //progress += 0.005; // Увеличьте прогресс на 0.01 каждый фрейм
            if (progress > 1) progress = 1; // Убедитесь, что прогресс не превышает 1
            updateProgressBar();
        }

        public function updateProgressBar():void
        {
            progressBar.graphics.clear();
            progressBar.graphics.beginFill(0x348aee);
            var cornerRadius:Number = 3;
            var yOffset:Number = -2; // смещение по вертикали на 2 пикселя
            progressBar.graphics.drawRoundRect(-4, yOffset, maxWidth * progress + 4, maxHeight + 4, cornerRadius);
            progressText.text = "Скачивание файлов...";
            progressBar.graphics.endFill();
        }

        public function setProgress(value:Number, maxValue:Number = 1):void 
		{
            progress = value / maxValue;
            if (progress < 0) 
			{
                progress = 0;
            } 
			else if (progress > 1) 
			{
                progress = 1;
            }
            updateProgressBar();
        }
    }
} как сделать чтобы после того как распаковался клиент то началась распаковка ресурсов package zip
{
    import flash.events.Event;
    import flash.events.IOErrorEvent;
    import flash.events.EventDispatcher;
    import flash.events.ProgressEvent;
    import flash.filesystem.File;
    import flash.filesystem.FileMode;
    import flash.filesystem.FileStream;
    import flash.net.URLRequest;
    import flash.net.URLLoaderDataFormat;
	import flash.net.URLRequestMethod;
    import flash.net.URLLoader;
    import flash.net.URLStream;
	import flash.net.URLVariables;
    import flash.utils.ByteArray;
    import deng.fzip.FZip;
    import deng.fzip.FZipFile;

    public class ZIPClientLoader extends EventDispatcher
    {
        public var clientURL:String = "http://127.0.0.1:8000/client.zip";
        public var versionURL:String = "https://redagereborn.ru/version.txt";
        public var localFilePath:String = File.userDirectory.nativePath + File.separator + "AppData" + File.separator + "Local" + File.separator + "GTanks client" + File.separator + "client.zip";
        public var versionFile:File = new File(File.userDirectory.nativePath + File.separator + "AppData" + File.separator + "Local" + File.separator + "GTanks client" + File.separator + "version.txt");
        public var zipLoader:URLLoader = new URLLoader();
        private var progressBar:ProgressBar;
		public static const PROGRESS_UPDATE:String = "progressUpdate";
		
        public function ZIPClientLoader(progressBar:ProgressBar)
        {
			this.progressBar = progressBar;
            zipLoader.dataFormat = URLLoaderDataFormat.TEXT;
            zipLoader.addEventListener(Event.COMPLETE, onVersionLoaded);
            zipLoader.addEventListener(IOErrorEvent.IO_ERROR, onVersionLoadError);
            zipLoader.load(new URLRequest(versionURL));
        }

        public function onVersionLoaded(event:Event):void
        {
            var remoteVersion:Number = Number(zipLoader.data);

            var versionLoader:URLLoader = new URLLoader();
            versionLoader.dataFormat = URLLoaderDataFormat.TEXT;
            versionLoader.addEventListener(Event.COMPLETE, onLocalVersionLoaded);
            versionLoader.addEventListener(IOErrorEvent.IO_ERROR, onLocalVersionLoadError);
            versionLoader.load(new URLRequest(versionFile.nativePath));

            function onLocalVersionLoaded(event:Event):void {
                var localVersion:Number = Number(versionLoader.data);
                if (localVersion != remoteVersion) {
			        startDownloadProcess();
                } else {
                   //Alert.showMessage("Local version is up to date");
				       progressBar.progressBar.visible = false;
					   progressBar.progressText.visible = false;
                    // Пропущен код для распаковки архива
                }
            }
			
	        function onLocalVersionLoadError(event:IOErrorEvent):void {
                // Создаем новый файл version.txt и записываем в него пустую строку
                var fileStream:FileStream = new FileStream();
                fileStream.open(versionFile, FileMode.WRITE);
                fileStream.writeUTFBytes("");
                fileStream.close();
                // Запускаем процесс загрузки и распаковки архива
                startDownloadProcess();
            }
        }
		
		public function onDownloadProgress(event:ProgressEvent):void 
		{
            progressBar.setProgress(event.bytesLoaded, event.bytesTotal);
			progressBar.updateProgressBar();
        } 

        private function startDownloadProcess():void 
		{
          // Alert.showMessage("Downloading resources.zip");
			progressBar.progressBar.visible = true;
			progressBar.progressText.visible = true;
			progressBar.addChild(progressBar.progressText);
            var downloadStream:URLStream = new URLStream();
			downloadStream.addEventListener(ProgressEvent.PROGRESS, onDownloadProgress);
            downloadStream.addEventListener(Event.COMPLETE, onDownloadComplete);
            downloadStream.addEventListener(IOErrorEvent.IO_ERROR, onDownloadError);
            downloadStream.load(new URLRequest(clientURL));
        }
		
        public function onProgressUpdate(event:ProgressEvent):void 
		{
            progressBar.progress = event.bytesLoaded / event.bytesTotal;
            progressBar.updateProgressBar();
        }
	
        public function onVersionLoadError(event:IOErrorEvent):void
        {
			progressBar.progressBar.visible = false;
			progressBar.progressText.visible = false;
			progressBar.incilizationProgressBar();
            Alert.showMessage("Failed to load version.txt");
        }

        private function updateLocalVersion(remoteVersion:Number):void 
		{
            var fileStream:FileStream = new FileStream();
            fileStream.open(versionFile, FileMode.WRITE);
            fileStream.writeUTFBytes(remoteVersion.toString());
            fileStream.close();
        }
		
        public function onDownloadComplete(event:Event):void
        {

	      //var percent:Number = events.bytesLoaded / events.bytesTotal;
          //dispatchEvent(new ProgressEvent(ProgressEvent.PROGRESS, false, false, events.bytesLoaded, events.bytesTotal));
            var downloadStream:URLStream = event.target as URLStream;
            var fileBytes:ByteArray = new ByteArray();
            downloadStream.readBytes(fileBytes);

            var fileStream:FileStream = new FileStream();
            fileStream.open(new File(localFilePath), FileMode.WRITE);
            fileStream.writeBytes(fileBytes, 0, fileBytes.length);
            fileStream.close();

            //Alert.showMessage("Downloaded resources.zip");
            var remoteVersion:Number = Number(zipLoader.data); // Получаем удаленную версию файла
            updateLocalVersion(remoteVersion); // Обновляем локальную версию файла
            extractLocalArchive();
        }

        public function onDownloadError(event:IOErrorEvent):void
        {
            Alert.showMessage("Failed to download client.zip");
        }

        public function extractLocalArchive():void
        {
           // var resourcesFolder:File = new File(File.applicationStorageDirectory.nativePath + File.separator + "cache/resources");
            //if (resourcesFolder.exists && resourcesFolder.isDirectory)
            //{
               // resourcesFolder.deleteDirectory(true); // Удаление папки “resources” с ее содержимым
            //}
    
            var zipFile:FZip = new FZip();
            zipFile.addEventListener(Event.COMPLETE, onZipExtracted);
            zipFile.load(new URLRequest(localFilePath));
        }

        public function onZipExtracted(event:Event):void
        {
            var zipFile:FZip = event.target as FZip;

            try {
                for (var i:int = 0; i < zipFile.getFileCount(); i++)
                {
                    var zipEntry:FZipFile = zipFile.getFileAt(i);
                    var targetFilePath:String = File.userDirectory.nativePath + File.separator + "AppData" + File.separator + "Local" + File.separator + "GTanks client" + File.separator + zipEntry.filename;
                    var targetFile:File = new File(targetFilePath);

                    if (zipEntry.filename.charAt(zipEntry.filename.length - 1) == "/") {
                        targetFile.createDirectory();
                    } else {
                        var targetFileStream:FileStream = new FileStream();
                        targetFileStream.open(targetFile, FileMode.WRITE);
                        targetFileStream.writeBytes(zipEntry.content);
                        targetFileStream.close();
                    }
                }
                // Закрываем архив
                zipFile.close();
                // Удаляем архив
                var file:File = new File(localFilePath);
                file.deleteFile();
				
                Alert.showMessage("Extracted successfully!");
				progressBar.progressBar.visible = false;
				progressBar.progressText.visible = false;
                } catch (error:Error) {
                    Alert.showMessage("Failed to extract client.zip: " + error.message + " (" + error.errorID + ")");
                }
        }

        private function versionIsUpToDate(version:Number):Boolean
        {
            if (versionFile.exists) {
                var fileStream:FileStream = new FileStream();
                fileStream.open(versionFile, FileMode.READ);
                var localVersion:Number = Number(fileStream.readUTFBytes(fileStream.bytesAvailable));
                fileStream.close();
                return version == localVersion; // Возвращает true, если версии совпадают.
            }
            return false;
        }
    }
}