//	Altirra - Atari 800/800XL/5200 emulator
//	Copyright (C) 2009-2016 Avery Lee
//
//	This program is free software; you can redistribute it and/or modify
//	it under the terms of the GNU General Public License as published by
//	the Free Software Foundation; either version 2 of the License, or
//	(at your option) any later version.
//
//	This program is distributed in the hope that it will be useful,
//	but WITHOUT ANY WARRANTY; without even the implied warranty of
//	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//	GNU General Public License for more details.
//
//	You should have received a copy of the GNU General Public License
//	along with this program; if not, write to the Free Software
//	Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.

#ifndef f_AT_FDC_H
#define f_AT_FDC_H

#include <vd2/system/function.h>
#include <at/atio/diskimage.h>
#include <at/atcore/scheduler.h>

class ATDiskInterface;
class ATConsoleOutput;

class ATFDCEmulator final : public IATSchedulerCallback {
public:
	enum : uint32 { kTypeID = 'FDC ' };

	ATFDCEmulator();
	~ATFDCEmulator();

	void SetOnDrqChange(const vdfunction<void(bool)>& fn) {
		mpFnDrqChange = fn;
	}

	void SetOnIrqChange(const vdfunction<void(bool)>& fn) {
		mpFnIrqChange = fn;
	}

	void Init(ATScheduler *sch, bool use1MHzScheduler);
	void Shutdown();

	void DumpStatus(ATConsoleOutput& out);

	void Reset();

	void SetAccurateTimingEnabled(bool enabled);
	void SetMotorRunning(bool running);
	void SetCurrentTrack(uint32 halfTracks, bool track0);
	void SetDensity(bool mfm);
	void SetWriteProtectOverride(bool override) { mbWriteProtectOverride = override; }
	void SetDiskImage(IATDiskImage *image, bool diskReady);
	void SetDiskInterface(ATDiskInterface *diskIf);

	uint8 DebugReadByte(uint8 address) const;
	uint8 ReadByte(uint8 address);
	void WriteByte(uint8 address, uint8 value);

	void OnIndexPulse(bool asserted);

public:
	void OnScheduledEvent(uint32 id) override;

protected:
	enum State : uint32 {
		kState_Idle,
		kState_BeginCommand,
		kState_EndTypeICommand,
		kState_EndNonTypeICommand,
		kState_Restore,
		kState_Restore_Step,
		kState_Seek,
		kState_Step,
		kState_StepIn,
		kState_StepOut,
		kState_ReadSector,
		kState_ReadSector_TransferFirstByte,
		kState_ReadSector_TransferFirstByteNever,
		kState_ReadSector_TransferByte,
		kState_ReadSector_TransferComplete,
		kState_WriteSector,
		kState_WriteSector_InitialDrq,
		kState_WriteSector_CheckInitialDrq,
		kState_WriteSector_TransferByte,
		kState_WriteSector_TransferComplete,
		kState_ReadAddress,
		kState_ReadTrack,
		kState_WriteTrack,
		kState_WriteTrack_WaitHeadLoad,
		kState_WriteTrack_WaitIndexMarks,
		kState_WriteTrack_TransferByte,
		kState_WriteTrack_InitialDrqTimeout,
		kState_WriteTrack_Complete,
		kState_ForceInterrupt,
		kState_ForceInterrupt_2,
	};

	void AbortCommand();
	void RunStateMachine();
	void SetTransition(State nextState, uint32 ticks);
	void UpdateRotationalPosition();
	void FinalizeWriteTrack();

	ATScheduler *mpScheduler = nullptr;
	ATEvent *mpStateEvent = nullptr;

	State mState {};

	uint8 mRegCommand = 0;
	uint8 mRegTrack = 0;
	uint8 mRegSector = 0;
	uint8 mRegData = 0;
	uint8 mRegStatus = 0;
	bool mbRegStatusTypeI = false;
	bool mbDataReadPending = false;
	bool mbDataWritePending = false;
	bool mbIrqPending = false;

	uint32 mOpCount = 0;
	uint32 mTransferIndex = 0;
	uint32 mTransferLength = 0;
	uint8 mActiveSectorStatus = 0;
	uint32 mActivePhysSector = 0;
	uint32 mActiveOpIndexMarks = 0;

	uint32 mRotPos = 0;
	uint64 mRotTimeBase = 0;
	bool mbMotorRunning = false;
	bool mbIndexPulse = false;
	bool mbTrack0 = false;
	bool mbDiskReady = false;
	bool mbMFM = false;
	bool mbWriteProtectOverride = false;

	uint32 mWeakBitLFSR = 1;
	uint32 mPhysHalfTrack = 0;
	vdrefptr<IATDiskImage> mpDiskImage;
	ATDiskInterface *mpDiskInterface = nullptr;

	ATDiskGeometryInfo mDiskGeometry {};

	bool mbScheduler1MHz = false;
	bool mbUseAccurateTiming = false;
	uint32 mCyclesPerRotation = 0;
	uint32 mCyclesPerByte = kCyclesPerByte;

	vdfunction<void(bool)> mpFnDrqChange;
	vdfunction<void(bool)> mpFnIrqChange;

	vdblock<uint8> mWriteTrackBuffer;
	uint32 mWriteTrackIndex;

	uint8 mTransferBuffer[1024] = {};

	static constexpr uint32 kMaxBytesPerTrackFM = 3256;
	static constexpr uint32 kMaxBytesPerTrackMFM = 6512;
	static constexpr uint32 kWriteTrackBufferSize = kMaxBytesPerTrackMFM;

	static constexpr uint32 kCyclesPerRotation500KHz = 104166;
	static constexpr uint32 kCyclesPerRotation1MHz = 208333;

	// 4us per bit cell, 2 bit cells per data bit, 8 data bits per byte, and 2us per cycle (500KHz)
	static constexpr uint32 kCyclesPerByte = 32;
};

#endif
