package miner

import (
    "fmt"
	"bytes"
	"errors"
{{if (le .v 1)}}
	"github.com/filecoin-project/go-state-types/big"
{{end}}
	"github.com/filecoin-project/go-bitfield"
	rle "github.com/filecoin-project/go-bitfield/rle"
	"github.com/filecoin-project/go-state-types/abi"
	"github.com/filecoin-project/go-state-types/dline"
	"github.com/ipfs/go-cid"
	cbg "github.com/whyrusleeping/cbor-gen"
	"golang.org/x/xerrors"

	"github.com/filecoin-project/lotus/chain/actors/adt"
	"github.com/filecoin-project/lotus/chain/actors"
	actorstypes "github.com/filecoin-project/go-state-types/actors"
	"github.com/filecoin-project/go-state-types/manifest"

{{if (le .v 7)}}
    {{if (ge .v 3)}}
	    builtin{{.v}} "github.com/filecoin-project/specs-actors{{.import}}actors/builtin"
    {{end}}
        miner{{.v}} "github.com/filecoin-project/specs-actors{{.import}}actors/builtin/miner"
        adt{{.v}} "github.com/filecoin-project/specs-actors{{.import}}actors/util/adt"
{{else}}
	miner{{.v}} "github.com/filecoin-project/go-state-types/builtin{{.import}}miner"
	adt{{.v}} "github.com/filecoin-project/go-state-types/builtin{{.import}}util/adt"
	builtin{{.v}} "github.com/filecoin-project/go-state-types/builtin"
{{end}}
)

var _ State = (*state{{.v}})(nil)

func load{{.v}}(store adt.Store, root cid.Cid) (State, error) {
	out := state{{.v}}{store: store}
	err := store.Get(store.Context(), root, &out)
	if err != nil {
		return nil, err
	}
	return &out, nil
}

func make{{.v}}(store adt.Store) (State, error) {
	out := state{{.v}}{store: store}
	out.State = miner{{.v}}.State{}
	return &out, nil
}

type state{{.v}} struct {
	miner{{.v}}.State
	store adt.Store
}

type deadline{{.v}} struct {
	miner{{.v}}.Deadline
	store adt.Store
}

type partition{{.v}} struct {
	miner{{.v}}.Partition
	store adt.Store
}

func (s *state{{.v}}) AvailableBalance(bal abi.TokenAmount) (available abi.TokenAmount, err error) {
	defer func() {
		if r := recover(); r != nil {
			err = xerrors.Errorf("failed to get available balance: %w", r)
			available = abi.NewTokenAmount(0)
		}
	}()
	// this panics if the miner doesnt have enough funds to cover their locked pledge
	available{{if (ge .v 2)}}, err{{end}} = s.GetAvailableBalance(bal)
	return available, err
}

func (s *state{{.v}}) VestedFunds(epoch abi.ChainEpoch) (abi.TokenAmount, error) {
	return s.CheckVestedFunds(s.store, epoch)
}

func (s *state{{.v}}) LockedFunds() (LockedFunds, error) {
	return LockedFunds{
		VestingFunds:             s.State.LockedFunds,
		InitialPledgeRequirement: s.State.InitialPledge{{if (le .v 1)}}Requirement{{end}},
		PreCommitDeposits:        s.State.PreCommitDeposits,
	}, nil
}

func (s *state{{.v}}) FeeDebt() (abi.TokenAmount, error) {
	return {{if (ge .v 2)}}s.State.FeeDebt{{else}}big.Zero(){{end}}, nil
}

func (s *state{{.v}}) InitialPledge() (abi.TokenAmount, error) {
	return s.State.InitialPledge{{if (le .v 1)}}Requirement{{end}}, nil
}

func (s *state{{.v}}) PreCommitDeposits() (abi.TokenAmount, error) {
	return s.State.PreCommitDeposits, nil
}

// Returns nil, nil if sector is not found
func (s *state{{.v}}) GetSector(num abi.SectorNumber) (*SectorOnChainInfo, error) {
	info, ok, err := s.State.GetSector(s.store, num)
	if !ok || err != nil {
		return nil, err
	}

	ret := fromV{{.v}}SectorOnChainInfo(*info)
	return &ret, nil
}

func (s *state{{.v}}) FindSector(num abi.SectorNumber) (*SectorLocation, error) {
	dlIdx, partIdx, err := s.State.FindSector(s.store, num)
	if err != nil {
		return nil, err
	}
	return &SectorLocation{
		Deadline:  dlIdx,
		Partition: partIdx,
	}, nil
}

func (s *state{{.v}}) NumLiveSectors() (uint64, error) {
	dls, err := s.State.LoadDeadlines(s.store)
	if err != nil {
		return 0, err
	}
	var total uint64
	if err := dls.ForEach(s.store, func(dlIdx uint64, dl *miner{{.v}}.Deadline) error {
		total += dl.LiveSectors
		return nil
	}); err != nil {
		return 0, err
	}
	return total, nil
}

// GetSectorExpiration returns the effective expiration of the given sector.
//
// If the sector does not expire early, the Early expiration field is 0.
func (s *state{{.v}}) GetSectorExpiration(num abi.SectorNumber) (*SectorExpiration, error) {
	dls, err := s.State.LoadDeadlines(s.store)
	if err != nil {
		return nil, err
	}
	// NOTE: this can be optimized significantly.
{{if (ge .v 7) -}}
    // 1. If the sector is non-faulty, it will expire on-time (can be
	// learned from the sector info).
{{- else -}}
    // 1. If the sector is non-faulty, it will either expire on-time (can be
	// learned from the sector info), or in the next quantized expiration
	// epoch (i.e., the first element in the partition's expiration queue.
{{- end}}
{{if (ge .v 6) -}}
	// 2. If it's faulty, it will expire early within the first 42 entries
	// of the expiration queue.
{{- else -}}
	// 2. If it's faulty, it will expire early within the first 14 entries
	// of the expiration queue.
{{- end}}

	stopErr := errors.New("stop")
	out := SectorExpiration{}
	err = dls.ForEach(s.store, func(dlIdx uint64, dl *miner{{.v}}.Deadline) error {
		partitions, err := dl.PartitionsArray(s.store)
		if err != nil {
			return err
		}
		quant := s.State.QuantSpecForDeadline(dlIdx)
		var part miner{{.v}}.Partition
		return partitions.ForEach(&part, func(partIdx int64) error {
			if found, err := part.Sectors.IsSet(uint64(num)); err != nil {
				return err
			} else if !found {
				return nil
			}
			if found, err := part.Terminated.IsSet(uint64(num)); err != nil {
				return err
			} else if found {
				// already terminated
				return stopErr
			}

			q, err := miner{{.v}}.LoadExpirationQueue(s.store, part.ExpirationsEpochs, quant{{if (ge .v 3)}}, miner{{.v}}.PartitionExpirationAmtBitwidth{{end}})
			if err != nil {
				return err
			}
			var exp miner{{.v}}.ExpirationSet
			return q.ForEach(&exp, func(epoch int64) error {
				if early, err := exp.EarlySectors.IsSet(uint64(num)); err != nil {
					return err
				} else if early {
					out.Early = abi.ChainEpoch(epoch)
					return nil
				}
				if onTime, err := exp.OnTimeSectors.IsSet(uint64(num)); err != nil {
					return err
				} else if onTime {
					out.OnTime = abi.ChainEpoch(epoch)
					return stopErr
				}
				return nil
			})
		})
	})
	if err == stopErr {
		err = nil
	}
	if err != nil {
		return nil, err
	}
	if out.Early == 0 && out.OnTime == 0 {
		return nil, xerrors.Errorf("failed to find sector %d", num)
	}
	return &out, nil
}

func (s *state{{.v}}) GetPrecommittedSector(num abi.SectorNumber) (*SectorPreCommitOnChainInfo, error) {
	info, ok, err := s.State.GetPrecommittedSector(s.store, num)
	if !ok || err != nil {
		return nil, err
	}

	ret := fromV{{.v}}SectorPreCommitOnChainInfo(*info)

	return &ret, nil
}

func (s *state{{.v}}) ForEachPrecommittedSector(cb func(SectorPreCommitOnChainInfo) error) error {
{{if (ge .v 3) -}}
	precommitted, err := adt{{.v}}.AsMap(s.store, s.State.PreCommittedSectors, builtin{{.v}}.DefaultHamtBitwidth)
{{- else -}}
	precommitted, err := adt{{.v}}.AsMap(s.store, s.State.PreCommittedSectors)
{{- end}}
	if err != nil {
		return err
	}

	var info miner{{.v}}.SectorPreCommitOnChainInfo
	if err := precommitted.ForEach(&info, func(_ string) error {
		return cb(fromV{{.v}}SectorPreCommitOnChainInfo(info))
	}); err != nil {
		return err
	}

	return nil
}

func (s *state{{.v}}) LoadSectors(snos *bitfield.BitField) ([]*SectorOnChainInfo, error) {
	sectors, err := miner{{.v}}.LoadSectors(s.store, s.State.Sectors)
	if err != nil {
		return nil, err
	}

	// If no sector numbers are specified, load all.
	if snos == nil {
		infos := make([]*SectorOnChainInfo, 0, sectors.Length())
		var info{{.v}} miner{{.v}}.SectorOnChainInfo
		if err := sectors.ForEach(&info{{.v}}, func(_ int64) error {
			info := fromV{{.v}}SectorOnChainInfo(info{{.v}})
			infos = append(infos, &info)
			return nil
		}); err != nil {
			return nil, err
		}
		return infos, nil
	}

	// Otherwise, load selected.
	infos{{.v}}, err := sectors.Load(*snos)
	if err != nil {
		return nil, err
	}
	infos := make([]*SectorOnChainInfo, len(infos{{.v}}))
	for i, info{{.v}} := range infos{{.v}} {
		info := fromV{{.v}}SectorOnChainInfo(*info{{.v}})
		infos[i] = &info
	}
	return infos, nil
}

func (s *state{{.v}}) loadAllocatedSectorNumbers() (bitfield.BitField, error) {
	var allocatedSectors bitfield.BitField
	err := s.store.Get(s.store.Context(), s.State.AllocatedSectors, &allocatedSectors)
	return allocatedSectors, err
}

func (s *state{{.v}}) IsAllocated(num abi.SectorNumber) (bool, error) {
	allocatedSectors, err := s.loadAllocatedSectorNumbers()
	if err != nil {
		return false, err
	}

	return allocatedSectors.IsSet(uint64(num))
}

func (s *state{{.v}}) GetProvingPeriodStart() (abi.ChainEpoch, error) {
	return s.State.ProvingPeriodStart, nil
}

func (s *state{{.v}}) UnallocatedSectorNumbers(count int) ([]abi.SectorNumber, error) {
	allocatedSectors, err := s.loadAllocatedSectorNumbers()
	if err != nil {
		return nil, err
	}

	allocatedRuns, err := allocatedSectors.RunIterator()
	if err != nil {
		return nil, err
	}

	unallocatedRuns, err := rle.Subtract(
		&rle.RunSliceIterator{Runs: []rle.Run{ {Val: true, Len: abi.MaxSectorNumber} }},
		allocatedRuns,
	)
	if err != nil {
		return nil, err
	}

	iter, err := rle.BitsFromRuns(unallocatedRuns)
	if err != nil {
		return nil, err
	}

	sectors := make([]abi.SectorNumber, 0, count)
	for iter.HasNext() && len(sectors) < count {
		nextNo, err := iter.Next()
		if err != nil {
			return nil, err
		}
		sectors = append(sectors, abi.SectorNumber(nextNo))
	}

	return sectors, nil
}

func (s *state{{.v}}) GetAllocatedSectors() (*bitfield.BitField, error) {
	var allocatedSectors bitfield.BitField
	if err := s.store.Get(s.store.Context(), s.State.AllocatedSectors, &allocatedSectors); err != nil {
		return nil, err
	}

	return &allocatedSectors, nil
}

func (s *state{{.v}}) LoadDeadline(idx uint64) (Deadline, error) {
	dls, err := s.State.LoadDeadlines(s.store)
	if err != nil {
		return nil, err
	}
	dl, err := dls.LoadDeadline(s.store, idx)
	if err != nil {
		return nil, err
	}
	return &deadline{{.v}}{*dl, s.store}, nil
}

func (s *state{{.v}}) ForEachDeadline(cb func(uint64, Deadline) error) error {
	dls, err := s.State.LoadDeadlines(s.store)
	if err != nil {
		return err
	}
	return dls.ForEach(s.store, func(i uint64, dl *miner{{.v}}.Deadline) error {
		return cb(i, &deadline{{.v}}{*dl, s.store})
	})
}

func (s *state{{.v}}) NumDeadlines() (uint64, error) {
	return miner{{.v}}.WPoStPeriodDeadlines, nil
}

func (s *state{{.v}}) DeadlinesChanged(other State) (bool, error) {
	other{{.v}}, ok := other.(*state{{.v}})
	if !ok {
		// treat an upgrade as a change, always
		return true, nil
	}

	return !s.State.Deadlines.Equals(other{{.v}}.Deadlines), nil
}

func (s *state{{.v}}) MinerInfoChanged(other State) (bool, error) {
	other0, ok := other.(*state{{.v}})
	if !ok {
		// treat an upgrade as a change, always
		return true, nil
	}
	return !s.State.Info.Equals(other0.State.Info), nil
}

func (s *state{{.v}}) Info() (MinerInfo, error) {
	info, err := s.State.GetInfo(s.store)
	if err != nil {
		return MinerInfo{}, err
	}

{{if (le .v 2)}}
	wpp, err := info.SealProofType.RegisteredWindowPoStProof()
	if err != nil {
		return MinerInfo{}, err
	}
{{end}}
	mi := MinerInfo{
		Owner:            info.Owner,
		Worker:           info.Worker,
		ControlAddresses: info.ControlAddresses,

		PendingWorkerKey:  (*WorkerKeyChange)(info.PendingWorkerKey),

		PeerId:                     info.PeerId,
		Multiaddrs:                 info.Multiaddrs,
		WindowPoStProofType:        {{if (ge .v 3)}}info.WindowPoStProofType{{else}}wpp{{end}},
		SectorSize:                 info.SectorSize,
		WindowPoStPartitionSectors: info.WindowPoStPartitionSectors,
		ConsensusFaultElapsed:      {{if (ge .v 2)}}info.ConsensusFaultElapsed{{else}}-1{{end}},
		{{if (ge .v 9)}}
            Beneficiary:                info.Beneficiary,
            BeneficiaryTerm:        BeneficiaryTerm(info.BeneficiaryTerm),
            PendingBeneficiaryTerm: (*PendingBeneficiaryChange)(info.PendingBeneficiaryTerm),
        {{end}}
	}

	return mi, nil
}

func (s *state{{.v}}) DeadlineInfo(epoch abi.ChainEpoch) (*dline.Info, error) {
	return s.State.{{if (ge .v 4)}}Recorded{{end}}DeadlineInfo(epoch), nil
}

func (s *state{{.v}}) DeadlineCronActive() (bool, error) {
	return {{if (ge .v 4)}}s.State.DeadlineCronActive{{else}}true{{end}}, nil{{if (lt .v 4)}} // always active in this version{{end}}
}

func (s *state{{.v}}) sectors() (adt.Array, error) {
	return adt{{.v}}.AsArray(s.store, s.Sectors{{if (ge .v 3)}}, miner{{.v}}.SectorsAmtBitwidth{{end}})
}

func (s *state{{.v}}) decodeSectorOnChainInfo(val *cbg.Deferred) (SectorOnChainInfo, error) {
	var si miner{{.v}}.SectorOnChainInfo
	err := si.UnmarshalCBOR(bytes.NewReader(val.Raw))
	if err != nil {
		return SectorOnChainInfo{}, err
	}

	return fromV{{.v}}SectorOnChainInfo(si), nil
}

func (s *state{{.v}}) precommits() (adt.Map, error) {
	return adt{{.v}}.AsMap(s.store, s.PreCommittedSectors{{if (ge .v 3)}}, builtin{{.v}}.DefaultHamtBitwidth{{end}})
}

func (s *state{{.v}}) decodeSectorPreCommitOnChainInfo(val *cbg.Deferred) (SectorPreCommitOnChainInfo, error) {
	var sp miner{{.v}}.SectorPreCommitOnChainInfo
	err := sp.UnmarshalCBOR(bytes.NewReader(val.Raw))
	if err != nil {
		return SectorPreCommitOnChainInfo{}, err
	}

	return fromV{{.v}}SectorPreCommitOnChainInfo(sp), nil
}

func (s *state{{.v}}) EraseAllUnproven() error {
	{{if (ge .v 2)}}
		dls, err := s.State.LoadDeadlines(s.store)
		if err != nil {
			return err
		}

		err = dls.ForEach(s.store, func(dindx uint64, dl *miner{{.v}}.Deadline) error {
			ps, err := dl.PartitionsArray(s.store)
			if err != nil {
				return err
			}

			var part miner{{.v}}.Partition
			err = ps.ForEach(&part, func(pindx int64) error {
				_ = part.ActivateUnproven()
				err = ps.Set(uint64(pindx), &part)
				return nil
			})

			if err != nil {
				return err
			}

			dl.Partitions, err = ps.Root()
			if err != nil {
				return err
			}

			return dls.UpdateDeadline(s.store, dindx, dl)
		})
		if err != nil {
			return err
		}

		return s.State.SaveDeadlines(s.store, dls)
	{{else}}
		// field doesn't exist until v2
                return nil
	{{end}}
}

func (d *deadline{{.v}}) LoadPartition(idx uint64) (Partition, error) {
	p, err := d.Deadline.LoadPartition(d.store, idx)
	if err != nil {
		return nil, err
	}
	return &partition{{.v}}{*p, d.store}, nil
}

func (d *deadline{{.v}}) ForEachPartition(cb func(uint64, Partition) error) error {
	ps, err := d.Deadline.PartitionsArray(d.store)
	if err != nil {
		return err
	}
	var part miner{{.v}}.Partition
	return ps.ForEach(&part, func(i int64) error {
		return cb(uint64(i), &partition{{.v}}{part, d.store})
	})
}

func (d *deadline{{.v}}) PartitionsChanged(other Deadline) (bool, error) {
	other{{.v}}, ok := other.(*deadline{{.v}})
	if !ok {
		// treat an upgrade as a change, always
		return true, nil
	}

	return !d.Deadline.Partitions.Equals(other{{.v}}.Deadline.Partitions), nil
}

func (d *deadline{{.v}}) PartitionsPoSted() (bitfield.BitField, error) {
	return d.Deadline.{{if (ge .v 3)}}PartitionsPoSted{{else}}PostSubmissions{{end}}, nil
}

func (d *deadline{{.v}}) DisputableProofCount() (uint64, error) {
{{if (ge .v 3)}}
	ops, err := d.OptimisticProofsSnapshotArray(d.store)
	if err != nil {
		return 0, err
	}

	return ops.Length(), nil
{{else}}
	// field doesn't exist until v3
	return 0, nil
{{end}}
}

func (p *partition{{.v}}) AllSectors() (bitfield.BitField, error) {
	return p.Partition.Sectors, nil
}

func (p *partition{{.v}}) FaultySectors() (bitfield.BitField, error) {
	return p.Partition.Faults, nil
}

func (p *partition{{.v}}) RecoveringSectors() (bitfield.BitField, error) {
	return p.Partition.Recoveries, nil
}

func (p *partition{{.v}}) UnprovenSectors() (bitfield.BitField, error) {
	return {{if (ge .v 2)}}p.Partition.Unproven{{else}}bitfield.New(){{end}}, nil
}

func fromV{{.v}}SectorOnChainInfo(v{{.v}} miner{{.v}}.SectorOnChainInfo) SectorOnChainInfo {
	info := SectorOnChainInfo{
		SectorNumber:          v{{.v}}.SectorNumber,
		SealProof:             v{{.v}}.SealProof,
		SealedCID:             v{{.v}}.SealedCID,
		DealIDs:               v{{.v}}.DealIDs,
		Activation:            v{{.v}}.Activation,
		Expiration:            v{{.v}}.Expiration,
		DealWeight:            v{{.v}}.DealWeight,
		VerifiedDealWeight:    v{{.v}}.VerifiedDealWeight,
		InitialPledge:         v{{.v}}.InitialPledge,
		ExpectedDayReward:     v{{.v}}.ExpectedDayReward,
		ExpectedStoragePledge: v{{.v}}.ExpectedStoragePledge,
		{{if (ge .v 7)}}
		SectorKeyCID: v{{.v}}.SectorKeyCID,
        {{end}}
	}
	return info
}

func fromV{{.v}}SectorPreCommitOnChainInfo(v{{.v}} miner{{.v}}.SectorPreCommitOnChainInfo) SectorPreCommitOnChainInfo {
	ret := SectorPreCommitOnChainInfo{
		Info:               SectorPreCommitInfo{
			SealProof:     v{{.v}}.Info.SealProof,
			SectorNumber:  v{{.v}}.Info.SectorNumber,
			SealedCID:     v{{.v}}.Info.SealedCID,
			SealRandEpoch: v{{.v}}.Info.SealRandEpoch,
			DealIDs:       v{{.v}}.Info.DealIDs,
			Expiration:    v{{.v}}.Info.Expiration,
			UnsealedCid:   nil,
		},
		PreCommitDeposit:   v{{.v}}.PreCommitDeposit,
		PreCommitEpoch:     v{{.v}}.PreCommitEpoch,
	}

	{{if (ge .v 9)}}
        ret.Info.UnsealedCid = v{{.v}}.Info.UnsealedCid
    {{end}}
    
	return ret
}

func (s *state{{.v}}) GetState() interface{} {
	return &s.State
}

func (s *state{{.v}}) ActorKey() string {
    return manifest.MinerKey
}

func (s *state{{.v}}) ActorVersion() actorstypes.Version {
    return actorstypes.Version{{.v}}
}

func (s *state{{.v}}) Code() cid.Cid {
	code, ok := actors.GetActorCodeID(s.ActorVersion(), s.ActorKey())
	if !ok {
		panic(fmt.Errorf("didn't find actor %v code id for actor version %d", s.ActorKey(), s.ActorVersion()))
	}

	return code
}
